tiny-ecs-love-template/systems/collision-detection.lua

40 lines
1.5 KiB
Lua

collidingEntities = filteredSystem("collidingEntitites", {
velocity = T.XyPair,
position = T.XyPair,
size = T.XyPair,
canCollideWith = T.BitMask,
isSolid = Maybe(T.bool),
})
filteredSystem(
"collisionDetection",
{ position = T.XyPair, size = T.XyPair, canBeCollidedBy = T.BitMask, isSolid = Maybe(T.bool) },
-- Here, the entity, e, refers to some entity that a moving object may be colliding *into*
function(e, _, system)
for _, collider in pairs(collidingEntities.entities) do
if
(e ~= collider)
and collider.canCollideWith
and e.canBeCollidedBy
and bit.band(collider.canCollideWith, e.canBeCollidedBy) ~= 0
then
local colliderTop = collider.position.y
local colliderBottom = collider.position.y + collider.size.y
local entityTop = e.position.y
local entityBottom = entityTop + e.size.y
local withinY = (entityTop > colliderTop and entityTop < colliderBottom)
or (entityBottom > colliderTop and entityBottom < colliderBottom)
if
withinY
and collider.position.x < e.position.x + e.size.x
and collider.position.x + collider.size.x > e.position.x
then
system.world:addEntity({ collisionBetween = { e, collider } })
end
end
end
end
)