Moving the Ball in Pong
April 17, 2008 — JesseAfter spending the last couple days reading and thinking, I finally got the ball to move in Pong. It’s probably not the most elegant solution but it works for now. The idea is that I want the ball to move in a random direction at the start of the game then I want it to bounce off the top and off the sides of the screen when it hits the edge. To calculate a random direction, I need a random number generator. For this reason, I need to include ctime and cstdlib headers in order to use time(), rand(), and srand(). I call srand() to seed a random number then I use the modulus operator with rand() to limit the range of numbers. For example, I can get the equivalent of a coin flip by calling rand() then taking a modulus 2.
To move the ball, I call move() and pass in the changes which I call dx and dy. These variable names are adopted from differential calculus and they hold the change in the x and y values. When the ball hits the edge of the screen, we have the following:
Looking at the diagram, it’s clear from basic trigonometry that the new angle will be the negative of the angle of reflection. For example, if the ball hits a wall going in a straight line, , then it will bounce back at
. Same thing goes for any other angle. So all I need to do to simulate the reflection is to multiply by a negative:
. This gives me the new direction but at the same speed. Because it looks like the ball goes off the screen, I won’t let the ball reach the end. Instead I’ll make it bounce when it’s about 10 pixels from the side of the screen or 20 pixels from the top and bottom of the screen. The eye will be fooled into thinking the ball hit the edge and reflected.
I inserted those two code snippets at the appropriate places in my code and when I ran the game– unbelievably, I have a moving ball. Now I just need collision detection… (The following Youtube video plays a little jerky but the game does not. It’s probably the compression that makes it look choppy.)


