Drawable ImagesTopAnimationsExplaining "Real" Pong

Explaining "Real" Pong

Let's get more realistic now and look at the real pong ball in file PongBall with main program Pong Notice that it uses an animator.while loop just like last time. However, this time the body is more complex!

Let's go through the differences between the PongBall class here and the FallingBall class in PatheticPong.

  1. The ball travels at randomly chosen speeds in the x and y directions. Thus rather than falling straight down, the ball also travels to the side, providing more interesting behavior. The initial speeds are chosen in the constructor of the ball using a random number generator that provides numbers (not just integers).

  2. When the ball hits the edges of the court or the paddle it bounces back. If the ball goes off the left side, the speed in the x direction is reversed (while the speed in the y direction is unchanged) and the ball is moved back to the edge of the course (i.e., we always keep it in the court). Similarly for the right side. The top is similar except we reverse the y speed.

  3. If the ball overlaps the paddle (notice the overlap method from the objectdraw library) with the top of the ball in the upper half of the paddle, then the y speed is reset to be negative.

  4. Notice that the ball cannot be off the left and right sides at the same time. He we use the elseif construct so that if it is off the left we don't bother to check the right. Similarly with top and bottom. However it could be both off the top and the left simultaneously (e.g. in the upper left corner), so just because it went off one side we still must check top and bottom.

One last secret: You will notice that if you click many times and generate lots of balls then the balls will slow down because it takes too much time to move them all. To adjust for this we will measure the elapsed time since the previous move and move the ball proportional to that. That is, we will have a constant speed (distance per millisecond), but before moving the ball we will multiply the speed by the amount of time that has elapsed.

For example if a car is moving at 60 mph then after 2 hours it should have gone 60*2 = 120 miles.

To do this, we measure the elapsed time between when the ball was last drawn and the time it is to be drawn again. The amount to be moved in each direction is determined by multiplying the speed (per millisecond) by the elapsed time. See NormalizedPongBall


Drawable ImagesTopAnimationsExplaining "Real" Pong