Simple Game Programming In JavaScript / Page 3 | WebReference

Simple Game Programming In JavaScript / Page 3

[previous] [next]

Simple Game Programming In JavaScript [con't]

The Key Events

Our game uses key presses to move the paddles up and down. We're also going to use a key press to serve the ball after the game has started so that players don't always have to use the mouse to press the "start game" button.

First, add these variables to the group up at the top of pingpong.js. You can change the characters between the single quotes to be whatever keys you want to press to move the paddles.

In goRight() and goLeft() we have one major change. Instead of changing directions when we hit the edges of the court we call the score() function and tell it which side just scored. The side opposite the direction of travel scores, since that side is the last side to have hit the ball. Other than that, the direction functions are just like they were at the end of the last tutorial.

The Paddle Functions

In order for animBall() to work at all, we need PadLoc(), which was called in line 27 of our big code block on page two.

Finally, add the event listener into your opening body tag like this: