boundingbox collision help

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
laurad
Prole
Posts: 6
Joined: Thu Jan 30, 2014 7:20 am

boundingbox collision help

Post by laurad »

Hi
I have copied this function from the wiki but when I run the game I get this error main.lua:107: ')' expected near '.'
I don't get what the problem is

Code: Select all

function CheckCollision(ball.x,ball.y,ball.width,ball.height,player2.x,
player2.y,player2.width,player2.height)
	return ball.x < player2.x+player2.width and
         player2.x < ball.x+ball.width and
         ball.y < player2.y+player2.height and
         player2.y < ball.y+ball.height
end
User avatar
micha
Inner party member
Posts: 1083
Joined: Wed Sep 26, 2012 5:13 pm

Re: boundingbox collision help

Post by micha »

Hi and welcome to the forum,

The code throws an error, because you have table entries in the list of passed values. That does not work. Try this instead:

Code: Select all

function CheckCollision(x1,y1,w1,h1,x2,y2,w2,h2)
	return x1 < x2+w2 and
         x2 < x1+w1 and
         y1 < y2+h2 and
         y2 < y1+h1
end
You could, of course, come up with names, that more speak for themselves.
Note: To call the function you can still pass tables entries:

Code: Select all

if CheckCollision(ball.x,ball.y,ball.width,ball.height,player2.x,
player2.y,player2.width,player2.height) then
  -- code
end
laurad
Prole
Posts: 6
Joined: Thu Jan 30, 2014 7:20 am

Re: boundingbox collision help

Post by laurad »

Thanks. I am trying to make pong and I am checking whether there is a collision between the ball and player2. So how would I use the if statement then

Code: Select all

if CheckCollision(ball.x,ball.y,ball.width,ball.height,player2.x,
player2.y,player2.width,player2.height) then
  -- code
end
User avatar
micha
Inner party member
Posts: 1083
Joined: Wed Sep 26, 2012 5:13 pm

Re: boundingbox collision help

Post by micha »

In pong you have two things to do after collision: 1) Resolve the collision, 2) Reflect the balls velocity.

I am assuming that player 2 is on the right side of the screen (for the player on the left you have to adapt the code accordingly).

Code: Select all

-- resolve collision
ball.x = player2.x - ball.width
-- reflect ball velocity
ball.velocityX = - ball.velocityX
Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests