I'm trying to collide my character with a table of boxes. I'm using the box collision shown in the wiki. I can get it to work without the else statement. But when I add it, collision doesn't happen.
for i = 1, table.getn(level.boxes) do
if CheckCollision(player.pos.x, player.pos.y, player.image:getWidth(), player.image:getHeight(),
level.boxes[i].x, level.boxes[i].y,level.boxes[i].width, level.boxes[i].height)
then
player.onGround = true
end
end
for i = 1, table.getn(level.boxes) do
if CheckCollision(player.pos.x, player.pos.y, player.image:getWidth(), player.image:getHeight(),
level.boxes[i].x, level.boxes[i].y,level.boxes[i].width, level.boxes[i].height)
then
player.onGround = true
else
player.onGround = false
end
end
I suspect you may want to 'break' if the player is found to be on the ground. Also, it would be a bit neater if you used 'pairs' to iterate the table. Lastly, no need to do the 'getWidth' and 'getHeight' calls for each iteration:
local onGround = false
local pw, ph = player.image:getWidth(), player.image:getHeight()
for i, v in pairs(level.boxes) do
if CheckCollision(player.pos.x, player.pos.y, pw, ph, v.x, v.y,v.width, v.height) then
onGround = true
break
end
end
player.onGround = onGround
pairs will still iterate over integer keys but the order in which it does so is not guaranteed and it will also iterate over anything else in the table, so yes, use ipairs on array-tables.