Game Development Reference
In-Depth Information
Furthermore, we would like to be able to
loop
our animation, meaning that once we
reach the last frame, the first frame should be shown again afterwards. Looping an
animation is very useful. In the case of a walking character, we only have to draw
one walk cycle and then loop the animation to get a continuous walking motion. Not
all animations should be looped though. For example, a dying animation should not
be looped (that would be very cruel to the character). So we want to
choose
if an
animation should be looped or not. For that, we declare a
bool
variable:
protected bool
isLooping;
In the constructor of the
Animation
class, we assign values to each of these member
variables:
public
Animation(
string
assetname,
bool
isLooping,
float
frametime = 0.1f)
:
base
(assetname, 0, "")
{
this
.frameTime = frametime;
this
.isLooping = isLooping;
}
We added a few convenient properties to the
Animation
class to access the different
member variables, as well as a few properties and methods related to playing an
animation. Furthermore, there is one additional member variable;
time
. This variable
is used to maintain how long we still need to show the current frame, as we will
explain later on.
26.4 Playing an Animation
The
Animation
class provides us with a few useful methods and properties for dealing
with animated sprites. Now, we still need to be able to play an animation. What does
'playing' mean exactly? It means that we have to determine which frame should be
shown depending on the time that has passed, as well as drawing that frame on the
screen. Calculating which frame should be drawn is something we do in the
Update
method of the
Animation
class. Since each frame in the animation corresponds to a
certain sheet index, we simply have to calculate which sheet index corresponds to
the current frame. The
Draw
method that is inherited from
SpriteSheet
does not have
to be modified.
In order to start playing the animation, we have to reset the values of the member
variables. We add a method called
Play
that does this:
public void
Play()
{
this
.sheetIndex = 0;
this
.time = 0.0f;
}