'Lua Tilemap collision handling
I am working on a platforming game and i am trying to get the collision detection to work, and failed miserably (the player does not detect anything). I wasn't able to find any help despite browsing every source that i can find. And so i am here to somehow get a helping hand.
function checkCollider(object1, object2, dir)
local w, h = _G.res.getSpriteBounds(object1.sprite) -- map
local w2, h2 = _G.res.getSpriteBounds(object2.sprite) -- player
local left1 = object1.x
local left2 = object2.x
local right1 = object1.x + w
local right2 = object2.x + w2
local top1 = object1.y
local top2 = object2.y
local bottom1 = object1.y + h
local bottom2 = object2.y + h2
if (dir == 0 and right1 < left2) then
return false;
end
if (dir == 1 and left1 < right2) then
return false;
end
if (dir == 2 and bottom1 < top2) then
return false;
end
if (dir == 3 and top1 < bottom2) then
return false;
end
return true; -- collided
--[[
if(dir == 1) then
if (bottom1 < top2) then return nil end; vertical
if (top1 > bottom2) then return nil end;
end
if(dir == 0) then
if (right1 < left2) then return nil end; horizontal
if (left1 > right2) then return nil end;
end
if(dir == 2) then
if (right1 < left2) then return nil end; both vertical and horizontal
if (left1 > right2) then return nil end;
if (bottom1 < top2) then return nil end;
if (top1 > bottom2) then return nil end;
end
return true collided
]]
end
here's the code that uses the collider function.
for k, v in _G.pairs(self.pixelNameTable) do
local map = self:getChild(v.name)
-- if the player has collided with a block that is not the void
if (checkCollider(map, player, 0) or checkCollider(map, player, 1)
or checkCollider(map, player, 2) or checkCollider(map, player, 3)) and map.sprite ~= "" then
player.tile = v.type -- collision detected, stop the player
else
player.tile = 0 -- collision not detected, free the player
end
end
I hope everything i said is clearly understandable.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
