Explaining "Real" Pong
Now that we understand how to perform animations with classes that
extend ActiveObject, it is easier to explain the more complex
behavior of the ball in the actual pong
game.
Let's go through the differences between the MovingBall class
here and the FallingBall class in PatheticPong.
- 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 doubles. The value given by
the random number generator is divided by the declared pause time,
so that later when the distance moved is multiplied by the actual
pause time, the resulting distance will be similar to the numbers
given by the random number generator.
- When the ball hits the edges of the court or the paddle it
bounces back. If it goes off the right side then the x speed
turns negative, if it goes off the left side then the x speed
is set to be positive. If it goes off the top, then the y speed
is set to be positive. If it 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. [Notice that some of these tests were based on
seeing how the animations looked. For example the ball could be
several pixels over the court boundary when its speed is changed,
but the eye doesn't see that.]
- Once started, each ball maintains its speed, even if the
system pauses for a greater time length than was provided in the
pause method. 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.