Game Development Reference
In-Depth Information
Next you have to translate and rotate the canvas context while taking the sprite's mirrored state into
account. That isn't covered in detail here, but you can have a look at the Canvas2D class to see how
it's done. To conclude the input handling, you set the mirror status according to the velocity if the
player is moving:
if (this.velocity.x != 0)
this.mirror = this.velocity.x < 0;
In the update method, you select which animation to play based on the velocity. If the velocity is
zero, you play the idle animation; otherwise you play the run animation:
if (this.velocity.x === 0)
this.playAnimation("idle");
else
this.playAnimation("run");
Finally, you call the update method in the base class to make sure the animation game-object version
of the update method is called as well.
To test your animation class, you create a single AnimationState instance, which you add to the
game-state manager:
ID.game_state_animation = powerupjs.GameStateManager.add(new AnimationState());
powerupjs.GameStateManager.switchTo(ID.game_state_animation);
In the AnimationState class, you create a Player instance, set it at the desired position, and add it to
the game world:
function AnimationState(layer) {
powerupjs.GameObjectList.call(this, layer);
var player = new Player();
player.position = new powerupjs.Vector2(50, 300);
this.add(player);
}
If you run the program, you see an animated character that you can control with the left and right
arrow keys (see Figure 25-2 ). If the character walks off the visible screen, it doesn't just “stop” off-
screen—it keeps going. So, if you hold down the right arrow key for 5 seconds, you need to hold the
left arrow key for 5 seconds as well to get the character back.
 
Search WWH ::




Custom Search