summaryrefslogtreecommitdiff
path: root/collisions.lua
blob: 093d57c0d96861a814c624d4e500c7ad5dfc153d (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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
function is_colliding(a, b)
    return (
        a.top_left.x < b.bottom_right.x and a.bottom_right.x > b.top_left.x
        and a.top_left.y < b.bottom_right.y and a.bottom_right.y > b.top_left.y
    )
end

_kills = {
    vec2(Entities.Sword, Entities.Bullet)
}
function kills(a, b)
    return some(_kills, function (v) return a.entity_type == v.x and b.entity_type == v.y end)
end
_consume = {
    -- Consume the bullet as soon as it hits a target
    vec2(Entities.Player, Entities.Bullet), 
    vec2(Entities.Wife, Entities.Bullet)
}
function consume(a, b)
    return some(_consume, function (v) return a.entity_type == v.x and b.entity_type == v.y end)
end
_hurts = {
    vec2(Entities.Bullet, Entities.Player),
    vec2(Entities.Sword, Entities.Enemy),
    vec2(Entities.Enemy, Entities.Player)
}
function hurts(a, b)
    if b:is_in_iframe() then
        return false
    end
    if not (a.damage and b.health) then
        return false
    end
    return some(_hurts, function (v) return a.entity_type == v.x and b.entity_type == v.y end)
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 hurts(a, b) then
        b:take_damage(a.line_of_sight, a.damage)
        if consume(b, a) then
            a:kill()
        end
    end
    if kills(a, b) then
        b:kill()
    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:collision_box(), b:collision_box()) then
                handle_collision(a, b)
            end
            ::continue::
        end
    end
end