Prev Up Next
Go backward to Drawing the Ball
Go up to Top
Go forward to Bouncing

Moving the Ball

Getting the ball to move isn't too hard either. For the x coordinate of the ball you have one variable, "x", for the current value of the coordinate and another, "xspeed", for how much this coordinate should change during each animation step. To tell the computer to actually change the coordinate, add the assignment

x = x + xspeed;
to the "animate" method before the "fillOval" that draws the ball. This assignment will tell the computer to set the ball's new x coordinate equal to the value of its current x coordinate plus the speed at which you want the ball to move from left to right.

Add a similar assignment for the y coordinate.

Run your applet again. If all is well, the ball should appear near the top of the screen and then move down the screen until it either falls off the bottom or side of the applet's screen area. Since you haven't added instructions to make the ball bounce, that is the last you will see of it. Once it disappears, select "quit" from the "File" menu to stop the animation (it is still drawing the ball somewhere you can't see it).

If it disappeared off the bottom rather than the side, make the initial speed in the x direction larger and run the applet again until you have adjusted the initial speed so that the ball does disappear off the right side of the applet's screen region.


Prev Up Next