Tearing my hair out over collision

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
danlthemanl
Prole
Posts: 11
Joined: Fri Jun 04, 2010 1:11 am

Tearing my hair out over collision

Post 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
User avatar
ivan
Party member
Posts: 1915
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

Re: Tearing my hair out over collision

Post 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
danlthemanl
Prole
Posts: 11
Joined: Fri Jun 04, 2010 1:11 am

Re: Tearing my hair out over collision

Post by danlthemanl »

thank you, that fixed my problem! You lifesaver you! :ultrahappy:
User avatar
Robin
The Omniscient
Posts: 6506
Joined: Fri Feb 20, 2009 4:29 pm
Location: The Netherlands
Contact:

Re: Tearing my hair out over collision

Post by Robin »

Better use ipairs here, btw. pairs is for iterating over keys that aren't integers between 1 and #level.boxes inclusive.
Help us help you: attach a .love.
User avatar
slime
Solid Snayke
Posts: 3161
Joined: Mon Aug 23, 2010 6:45 am
Location: Nova Scotia, Canada
Contact:

Re: Tearing my hair out over collision

Post 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. ;)
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot] and 1 guest