Game Development Reference
In-Depth Information
As mentioned, the AnimatedGameObject class is a subclass of SpriteGameObject . That means when
this object is drawn on the screen, it tries to draw the sprite sheet that the member variable sprite
points to. However, note that you pass null as a parameter when you call the base constructor in
the AnimatedGameObject constructor:
function AnimatedGameObject(layer, id) {
powerupjs.SpriteGameObject.call(this, null , layer, id);
...
}
You need to assign the sprite belonging to the currently running animation to the sprite member
variable so this animation is then drawn on the screen. You can easily do this, because each
Animation instance contains a reference to the sprite that it should animate. Assigning this sprite to
the sprite member variable is done in the playAnimation method.
In that method, you first check whether the animation you want to play is already playing. If it is, you
don't have to do anything else and you can return from the method:
if (this._current === this._animations[id])
return;
Next, you set the current sheet index and the _time variable to 0, and you assign the currently active
animation according to the ID that was passed along as a parameter:
this._sheetIndex = 0;
this._time = 0;
this._current = this._animations[id];
Finally, you set the sprite member variable to the sprite that should be drawn:
this.sprite = this._current.sprite;
Playing an Animation
You've defined a few useful classes and methods for loading and selecting animations. You still need
to be able to play an animation. What does playing mean, exactly? It means you have to determine
which frame should be shown, depending on the time that has passed, and draw that frame on the
screen. Calculating which frame should be drawn is something you do in the update method of the
AnimatedGameObject class. Because each frame in the animation corresponds to a certain sheet
index, you simply have to calculate which sheet index corresponds to the current frame. The draw
method inherited from SpriteGameObject doesn't have to be modified.
In the update method, you have to calculate which frame should be drawn. But that means you need
to know how much time has passed since the last frame was drawn. If you were to increment the
frame index in every call to the update method, the animation would be played much too fast. So,
you save the time that has passed since the last frame was drawn in the member variable _time .
You update this variable in the beginning of the update method:
this._time += delta;
 
Search WWH ::




Custom Search