Game Development Reference
In-Depth Information
Now you can calculate the index of the frame that should be shown. For this, you use a
while
instruction:
while (this._time > this._current.frameTime) {
this._time -= this._current.frameTime;
this._sheetIndex++;
if (this._sheetIndex >=this.sprite.nrSheetElements)
if (this._current.looping)
this._sheetIndex = 0;
else
this._sheetIndex = this.sprite.nrSheetElements - 1;
}
What happens here? The
while
instruction continues as long as the
_time
variable contains a value
larger than
frameTime
. In the
while
instruction, you subtract the frame time from the
_time
variable.
Suppose the time that each frame is displayed is set to 1 second. You enter the
update
method and
add the elapsed time to the
_time
member variable. Suppose this variable now contains the value
1.02, meaning the frame you're currently showing has been shown for 1.02 seconds. This means
you should show the next frame instead. You do this by incrementing the index of the frame you're
currently showing, which is the second instruction in the
while
loop. You then update the
_time
variable and subtract the frame time (1 second), so the new value of
_time
becomes 0.02. You put
this code in a
while
instruction instead of an
if
instruction so you're sure you always show the right
frame, even if the time passed since the last update was multiple times the frame time. For example,
if the new value of
_time
was 3.4, you would need to move three frames ahead and subtract the
frame time three times from the
_time
variable. The
while
instruction takes care of that.
After incrementing the current frame index, you have to take care of what happens once you're
past the last frame. To do that, you check whether the sheet index is greater than or equal to
this.sprite.nrSheetElements
. Depending on whether you want the animation to loop, you either
reset the sheet index to 0 or set it to the last element in the sheet.
The Player Class
To use the
AnimatedGameObject
class introduced in the previous section, you inherit from it. Because
the player will control the animated character, let's define a
Player
class that is a subclass of
AnimatedGameObject
. In this class, you load the animations belonging to the player and handle the
input from the player. In the
Player
constructor, you load the animations that are needed for this
character. In this example, you want the character to walk or stand still. So, you load two animations
by calling the
loadAnimation
method twice. You want both of these animations to loop, so you set
the looping parameter to
true
:
this.loadAnimation(sprites.idle, "idle", true);
this.loadAnimation(sprites.run, "run", true, 0.05);
Search WWH ::
Custom Search