JavaScript and HTML5 – Simple Game Creation Tutorial (part 2a)

All of these changes are now incorporated into part 2 of the Simple Game tutorial

A slight errata is being made to the JavaScript code for part 2 of the Simple Game tutorial. I’ve had it pointed out to me by several people that the way the arrow keys interact with the hero character isn’t very intuitive. To remedy that we’re going to adjust the hero update function to take the most recent key that is pressed as the “active direction” for movement. Because of the way we are capturing keydown and keyup there are no required changes to that section of the code.

What we’ll do is change it from a series of if / else if conditional checks to a simple switch statement using the last key that was pushed into the array. Since we use push and splice to work with the array and we are always checking to see if a key is already in the array or not, we can be sure that the key code in the last index of the array will be the key that was most recently pressed down. Also, I’m going to take this opportunity to adjust the logic that updates the sprite. Previously, we were just doing a check of

to determine if we should update the sprite that we are displaying or not. This had the unfortunate side effect of not doing an immediate transition on the sprite when the hero changed directions. The fix for that is fairly straight forward and only requires that we check if the animation timer has elapsed or if the current sprite being shown isn’t one of the two valid sprites for the direction we are moving.

The new code that replaces the part 2 update function is:

Simple Game 2 - Sample Image

The code is update on the demo site in the SimpleGame_2.js file.