Putting it all together (Page 2 of 2)

Article by Matthew Casperson (4,883 pts ) , published Jul 3, 2009

If the player is not moving the updateRequired variable is set to true, which causes the updateAnimation function to be called. Otherwise we assume that the call to keyDown is because of the fact that it is called repeatedly when a key is held down, and no change to the animation is done. [code].

Unlike the keyDown function, the keyUp function doesn't get called repeatedly, and so we can modify the current animation back to the idle animation directly. We do still make a call to the updateAnimation function in keyUp because both the left and right arrow keys can be held down at the same time, and releasing one may still mean that the other is held down, meaning that we can't assume that releasing one key will necessarily drop the player back to the idle animation. [code]

Then there is the updateAnimation function itself, which sets the appropriate animation if the player is moving left, right, or standing still because (as mentioned above) both left and right arrow keys can be held down at the same time. [code]

The last change we need to make is to modify the xScroll value when the player reaches the edge of the screen. The xScroll and yScroll values represent how far the camera has moved left and right across the level. As the player moves right across the level the xScroll value needs to increase to keep the player on the screen. And conversely as the player moves left the xScroll value needs to decrease. The background images, represented by the RepeatingGameObjects created by the ApplicationManager, also use the xScroll values to scroll themselves, so by modifying the xScroll we get the illusion that the player is moving through the level. [code]

Check out the demo here, download the source code here, and browse the code documentation here.

Read more in the Game Development with JavaScript and the Canvas element series.

Images

 
Subscribe to Web Development
RSS
Get free weekly updates, directly to your inbox.
Browse Web Development