Prev Up Next
Go backward to Bouncing
Go up to Top
Go forward to Making the Paddle Useful

Adding a Paddle

The paddle is supposed to move whenever you move the mouse. So, you should expect to have to put some instructions in the "mouseMove" method to take care of the paddle when the browser tells you that the mouse has moved. The surprise is that you won't actually draw the paddle in mouseMove. Why? Remember that you placed a "clearRect" in "animate". This is necessary to remove old images of the ball from the screen. Since animate is invoked all the time, however, this "clearRect" would quickly remove any paddle drawn by "mouseMove".

The solution to this is to have "animate" draw the paddle at a location determined by a variable set by "mouseMove". The variable will keep track of the mouse's x coordinate the last time the browser invoked "mouseMove". So:

  1. Add a declaration for a new variable at the top of your applet. "lastX" or "paddleX" might be a good name.

  2. Add an assignment in the "mouseMove" method to set this new variable equal to the "x" parameter the browser passes to "mouseMove".

  3. Add a line to the end of "animate" to draw the paddle. You can do this using a fillRect. Make the paddle about 20 pixels wide. Draw it so that its center is located at the same x coordinate as the last mouse position. Make it 5 pixels high with a "top" y coordinate of 195. This will place it right at the bottom of the applet screen display.

If you run your applet now, you should be able to control the paddle with the mouse. You will notice (possibly with some frustration) that the applet ignores the mouse if you move the mouse pointer out of the applet display area. You will also notice that the ball still bounces off the bottom no matter where the paddle is.


Prev Up Next