Simple Game Programming In JavaScript / Page 2 | WebReference

Simple Game Programming In JavaScript / Page 2

[previous] [next]

Simple Game Programming In JavaScript [con't]

The JavaScript

Now that we've got the basic court created, let's start on the JavaScript. We'll put the JavaScript into its own file this time, so, up in the head area, add the line:

And then create the file pingpong.js for the JavaScript. We'll start with the pieces that we wrote for the last tutorial, with a few changes to fit our new needs.

The top of the script is a listing of the variables that we'll be using throughout this script. We set the directions on the x (horizontal) and y (vertical) axis to their primary direction, set the speed in the x axis to 10 (pixels per cycle) and the speed on the y axis to a random number. The timer control is set to 0. The four directions for the paddles are given values that we'll use later on to move the paddles with key commands. All other variables are left empty until they're filled up by the functions.

The big changes in animBall() in this script are the paddle controls. Right after defining the image and window (in this case div) heights and widths, we call the PadLoc() function to find out where the paddles are located. Then we check to see if the ball has reached the point to the left or right in the court where the paddles are. If they are, then we need to check if the ball has hit the paddle or not. We use rPadlHit() and lPadlHit() to check for a hit and to turn the ball around if it has hit a paddle. The rest of this function is the same as before.

The function setRand() is exactly as before. In the previous animation we used the random numbers for both x and y axis movement, though. This time, we only use random numbers for the y axis. The reason is that if both numbers are random you get a strange game of ping pong, indeed. The ball will sometimes move across the court very slowly and other times much too fast. If, however, you make both numbers constant, then the ball will always bounce in the exact same diagonal lines. Randomizing the y axis gives us some variation, while keeping the x axis stable gives us a playable game.

[previous] [next]