Allegro.cc Forums » Programming Questions » Make a ball bouncing?

 FrankyR Member #243 April 2000 Well, the best way to do this is to find the reflection vector for the ball after it hits the wall or paddle. This is really easy to do mathematically once you have the basics set up.First, you have to think about how the ball's position and velocity is represented. It's easiest to think of these as two vectors, each consisting of an "x" and a "y" component. //ball's position float x,y; //ball's velocity float dx,dy;  The dx and dy represent the velocity of the ball in the x and y directions (i.e. the amount to change the ball's x and y position each update.//in the ball's update function (assuming fixed time step): x+=dx; y+=dy;  In order to make the ball "bounce" off of a surface you just need to change its velocity (dx and dy) after the collision is resolved. This can be done using a dot product between the ball's velocity vector and the surface's normal, but if you're just doing a pong game you can get away with a simpler solution:If the ball is bouncing off of a vertical surface, then just reverse the x component of the ball's velocity (i.e. dx=-dx), and if the ball is bouncing off of a horizontal surface, then you just reverse the y component of the ball's velocity (i.e. dy=-dy). If you want to deal with surfaces that are not perfectly horizontal or vertical then you'll need to use a little bit of simple vector math (dot product).The other half of the problem is figuring out when the ball hits something that it needs to bounce off of. I'd recommend searching for "bounding box" collision detection for that.