Simple Game Programming In JavaScript / Page 4 | WebReference

Simple Game Programming In JavaScript / Page 4


[previous] [next]

Simple Game Programming In JavaScript [con't]

The Directions

Our next chunk of code will make the ball move around. You'll see that these are similar to previous versions of these functions.

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 the same as they were at the end of the last tutorial.

The Paddle Functions

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

This function gives us important location information about the two paddles, and defines the variables rpadl, rInt, lpadl and lInt. As in the last animation, we need to use the built-in JavaScript function parseInt() to get the actual number values for the right and left paddles' style.top. We need the integer because you can't add or subtract a style attribute without converting it into a number first.

Since we're writing paddle functions, we might as well write the functions to handle the hits, as well.

You can see that we're using the integer values from the style.top for each of the paddles and then adding them to an integer conversion of the height of the paddles. If you try these without the parseInt() function wrapped around the styles, the script will break fatally.

How do we decide that a hit has occurred? imgTopInt is the point at the top of the ball image. rBottom and lBottom are the points at the bottom of the right and left paddles respectively.  rTop and lTop are the points at the top of the right and left paddles minus the image height. A hit happens when the ball reaches the edge of a paddle and is any part of the ball image, top to bottom, that touches any part of the paddle div.

And now we need the functions that will move the paddles.

With each of these functions we take an attribute dir in order to decide which direction the paddles should move. Direction 1 is up, direction 0 is down. Notice also that each side makes sure that the paddle doesn't go beyond 5 pixels beyond 320 pixels from the top. That ensures that the paddles don't go right off the edge of the court. We want our players in the court, not off in the stands with the fans.


[previous] [next]