aboutsummaryrefslogtreecommitdiff
path: root/bullets.lua
blob: 41ff210c2e32f9ce02e914d09e2aa19ac90acb78 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
bullets = {}

function addbullet(x, y, velx, vely, evil, sprite)
    local bullet = {}

    bullet.sprite = sprite
    bullet.evil = evil
    bullet.x = x
    bullet.y = y
    bullet.velx = velx
    bullet.vely = vely

    function bullet.draw(bullet)
        spr(bullet.sprite, bullet.x, bullet.y)
    end

    function bullet.collide(object)
        if bullet.x+4 >= object.x and bullet.x+4 <= object.x+object.w and bullet.y+4 >= object.y and bullet.y+4 <= object.y+object.h and object.inv < 0 then
            object:shot()
            del(obj, bullet)
        end
    end

    function bullet.accurate_collide(object)
        if bullet.x+4 >= object.x-2 and bullet.x+4 <= object.x+2+object.w and bullet.y+4 >= object.y-2 and bullet.y+4 <= object.y+object.h+2 then
            object:shot()
            del(obj, bullet)
        end
    end

    function bullet.update(bullet)
        --applying velocity
        bullet.x += bullet.velx
        bullet.y += bullet.vely

        --collision detection
        if bullet.evil then
            foreach(players, bullet.collide)
        elseif bullet.evil == false then
            foreach(enemies, bullet.accurate_collide)
        end

        --delete bullet if off screen
        if bullet.y > 128 or bullet.y < -8 or bullet.x > 128 or bullet.x < -8 then
            del(obj, bullet)
        end
    end

    add(obj, bullet)
    add(bullet, #obj)
end