Page 1 of 1
Apply noise to bounce
Posted: Mon Feb 19, 2018 10:13 am
by aidalgol
I'm trying to make a pong game, and I'm not sure how to introduce randomness to the angular velocity of the ball after it bounces off a paddle (which I want to do to make it a little less predictable than the original Pong). Each paddle is a static body, and the ball is a dynamic body with restitution of 0.9 on the ball's fixture. My first thought is to add noise to the ball's linear velocity vector in the endContact callback. Can anyone offer other approaches?
Re: Apply noise to bounce
Posted: Wed Feb 21, 2018 11:40 am
by PGUp
pong without physics.. its much better
Re: Apply noise to bounce
Posted: Wed Feb 21, 2018 12:52 pm
by zorg
What PGUp means is that usually, pong games aren't made with realistic physics engines like Box2D (what love.physics uses), although if you wanted to do it that way, it's not wrong per se; that said, if i'm not mistaken, the setLinearVelocity method of a body wants the dx and dy parameters; you'd need to math out the conversion from the cartesian to the polar coordinate system, so you'll have a magnitude and an angle instead of per-axis deltas; then you could add a small random amount to the angle, which will not mess up the overall speed of the ball, then you'll need to convert back to cartesian so you can actually set the value.
Thankfully, the conversions between the two coordinate systems are simple:
Code: Select all
-- to polar
r = math.sqrt(x^2 + y^2)
phi = math.atan2(y, x)
-- modify the angle by some amount (you could also incrementally increase the magnitude so it gradually speeds up...
phi = phi + (love.math.random()-0.5)*math.pi -- angles are in radians, so this will modify the angle by a maximum of ±90 degrees.
-- turn it back to cartesian
dx = r * math.cos( phi )
dy = r * math.sin( phi )
Re: Apply noise to bounce
Posted: Wed Feb 21, 2018 2:02 pm
by ivan
You can use preSolve to decide how your ball/paddle collision is resolved.
If you were to randomize the restitution and friction of the collision, you will get randomness that looks more or less plausible.
Make sure to use "Contact:setFriction" and "Contact:setRestitution" (friction affects the tangent and restitution affects the normal axis).
You have to change the friction/restitution of the actual contact, if you just changed it on the paddle it may not work as expected (since the ball's coefficients are important too).
Re: Apply noise to bounce
Posted: Sun Feb 25, 2018 2:18 am
by aidalgol
Thanks to everyone for their advice. I have started out using Box2D instead of just bump or HC because I wanted to add silly physics once I had a ball and two paddles. before zorg's post, I had implemented almost exactly that, but with randomNormal() instead of random(). I tried Ivan's suggestion of adding randomness to the friction and restitution, and just doing that results in velocity all over the place, so doing it in the endContact() callback is definitely easiest.