summaryrefslogtreecommitdiff
path: root/collisions.lua
blob: f57554e79f4d1037079f382277739a1adf71b595 (plain) (blame)
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
function is_colliding(a, b)
    ax1, bx1 = a.position.x, b.position.x
    ax2, bx2 = ax1 + SPRITE_DIMS.x, bx1 + SPRITE_DIMS.y
    ay1, by1 = a.position.y, b.position.y
    ay2, by2 = ay1 + SPRITE_DIMS.y, by1 + SPRITE_DIMS.x
    return (ax1 < bx2 and ax2 > bx1
                and ay1 < by2 and ay2 > by1)
end

function handle_collision(a, b)
    if a.entity_type == Entities.Sword and b.entity_type == Entities.Player and b.equipped[a.id] == nil then
        b:equip(a)
        return
    end
    if a.damage and b.health then
        if b:is_in_iframe() then
            return
        end
        b:take_damage(a.line_of_sight, a.damage)
    end
end

function run_collisions()
    collidable = filter(_World, function(e) return e.collision end)
    for _ai, a in pairs(collidable) do
        for _bi, b in pairs(collidable) do
            if a.id == b.id then
                goto continue
            end
            if is_colliding(a, b) then
                handle_collision(a, b)
            end
            ::continue::
        end
    end
end