Game Development Reference
In-Depth Information
Because the idle animation only contains a single sheet element, you don't need to specify the frame
time. For the running animation, you specify that each frame should be shown for five hundredths of
a second. When the application starts, the character's idle animation should play:
this.playAnimation("idle");
You also change the player's origin. If you want to draw animated characters moving on a floor, it's
useful to use a point on the bottom of the character sprite as its origin. Also, as you see later, this is
useful for collision checking. For these reasons, you define the origin of the player as the point in the
center of the bottom of the sprite element:
this.origin = new powerupjs.Vector2(this.width / 2, this.height);
Now you need to handle the player's input in this class. When the player presses the left or right
arrow key, the velocity of the character should change. You do this in the handleInput method, using
an if instruction:
var walkingSpeed = 400;
if (powerupjs.Keyboard.down(powerupjs.Keys.left))
this.velocity.x = -walkingSpeed;
else if (powerupjs.Keyboard.down(powerupjs.Keys.right))
this.velocity.x = walkingSpeed;
else
this.velocity.x = 0;
Note I chose a value of 400 for the walkingSpeed parameter. Play around with this value and see how
it changes the character's behavior. Choosing the right value for parameters such as this one has a big
influence on gameplay. It's important to choose values that are “just right.” Testing gameplay with a variety of
players can help you determine what these values should be so that the gameplay feels natural.
Using the sprite shown in Figure 25-1 allows you to animate a character walking to the right. To
animate a character walking to the left, you could use another sprite. However, there is an easier way
to accomplish this: by mirroring the sprite when you draw it. Mirroring sprites can be useful for any
kind of sprite game object, so in the SpriteGameObject class, you add a member variable mirror ,
which indicates whether the sprite should be mirrored. In the draw method of SpriteSheet , you pass
along the value of the mirror variable to Canvas2D.drawImage , as follows:
powerupjs.Canvas2D.drawImage(this._image, position, 0, 1, origin, imagePart,
mirror);
You have to extend Canvas2D so it supports drawing a mirrored sprite. You do this by scaling the
sprite negatively , using the following instruction:
if (mirror) {
this._canvasContext.scale(scale * canvasScale.x * -1, scale *
canvasScale.y);
...
}
 
 
Search WWH ::




Custom Search