Page 1 of 1

How can I make a ball bounce when it collisions

Posted: Mon May 08, 2023 5:42 pm
by Abiii
I am making a pong game and I was wondering how could I do for the ball to move randomly in any direction and make it bounce when it touches the paddle

Re: How can I make a ball bounce when it collisions

Posted: Mon May 08, 2023 8:19 pm
by dusoft
Do you use love.physics for movement? If so, you will need to look into setting callbacks:
https://love2d.org/wiki/World:setCallbacks

e.g. beginContact function to change its direction by using applyAngularImpulse / applyForce:
https://love2d.org/wiki/Body:applyAngularImpulse
(probably applying opposite direction to current angle / inverted angle)

Re: How can I make a ball bounce when it collisions

Posted: Tue May 09, 2023 8:06 am
by darkfrei
Normally just invert one of axis velocities:

Code: Select all

vx = -vx
-- or
vy = -vy

Re: How can I make a ball bounce when it collisions

Posted: Tue May 09, 2023 10:59 pm
by Bigfoot71
For a random direction you can do (only for diagonal moves):

Code: Select all

vx = math.random() < 0 and -1 or 1
vy = math.random() < 0 and -1 or 1
Or for an entirely random direction you could also do something like this

Code: Select all

local a = math.random() * (math.pi*2)
local vx = math.cos(a)
local vy = math.sin(a)
If you opt for the first solution then for the bounce the Darkfrei solution will be the right one (as well as the best for a pong I presume), but if you want a more precise physics by opting for the second solution you can apply the reflection of the velocity vector but this is more technical if you are a beginner or not comfortable with math.

I still gave you a quick example of this method, the ball will not go in the same direction depending on where it hits the racket, that is to say that if it hits all to the right of the racket the ball will go all the way on the right, if it hits the center it will go straight, etc...

Edit: Sorry for the typo, it should be 'math.random < 0.5' instead of 'math.random < 0' because 'math.random' without a parameter returns floating-point numbers between 0 and 1.

Re: How can I make a ball bounce when it collisions

Posted: Wed May 10, 2023 5:01 am
by pgimeno
Generally, in a Pong game the collisions will be against axis-aligned surfaces, so darkfrei's method works fine as a crude approximation. For a more precise response, Bump's "Bounce" collision resolution works better, especially at higher ball speeds.

But yeah, it's interesting to make it behave as if the racket was curved, to give the player some degree of control over the direction of the shot.