Page 1 of 1

Tearing my hair out over collision

Posted: Tue Jun 21, 2011 12:54 am
by danlthemanl
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.

Works but won't unCollide

Code: Select all

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
Doesn't work at all

Code: Select all

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

Re: Tearing my hair out over collision

Posted: Tue Jun 21, 2011 3:40 am
by ivan
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:

Code: Select all

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

Re: Tearing my hair out over collision

Posted: Tue Jun 21, 2011 4:08 am
by danlthemanl
thank you, that fixed my problem! You lifesaver you! :ultrahappy:

Re: Tearing my hair out over collision

Posted: Tue Jun 21, 2011 6:16 am
by Robin
Better use ipairs here, btw. pairs is for iterating over keys that aren't integers between 1 and #level.boxes inclusive.

Re: Tearing my hair out over collision

Posted: Tue Jun 21, 2011 6:23 am
by slime
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. ;)