Game Development Reference
In-Depth Information
Instead of simply incrementing the current frame index, we do something slightly
more complicated to allow for looping behavior. For this, we use the modulo oper-
ationonthe
sheet_index
variable. As soon as the sheet index is larger or equal to
this
.NumberSheetElements
, the modulo operation resets the value of
sheet_index
to
zero by returning zero as the remainder of the division. The result is that the ani-
mation is looping. If we do not want to have looping behavior (this is the
else
part
of the
if
-instruction), then we calculate the new frame index by simply increment-
ing it. In order to avoid that we try to draw a frame outside of the sprite image, we
use the
Math.Min
method to ensure that the new frame index never is higher than
this
.NumberSheetElements
−
1
.
26.4.2 Mirroring Sprites
Simply using the sprite shown in Fig.
26.1
allows us to animate a character walk-
ing to the right. In order to animate a character walking to the left, we could use
another sprite. However, there is an easier way to accomplish this: by using sprite
effects. The
SpriteEffects
enumerated type allows specifying whether a sprite should
be flipped horizontally or vertically. A horizontal flip does exactly what we need
in this case: flip the image around the standing axis, resulting in a sprite animation
consistent with walking in the opposite direction. Mirroring sprites can be useful
for any kind of sprite, so inside the
SpriteSheet
class, we add a member variable
mirror
, which indicates if the sprite should be mirrored or not. We use this variable
to determine the desired sprite effect in the
Draw
method of the class:
SpriteEffects spriteEffects = SpriteEffects.None;
if
(mirror)
spriteEffects = SpriteEffects.FlipHorizontally;
spriteBatch.Draw(sprite, position, spritePart, Color.White,
0.0f, origin, 1.0f, spriteEffects, 0.0f);
26.5 An Animated Game Object
The
Animation
class provides the ground work for playing animations. In this section,
we will introduce a new kind of game object: the
animated
game object, which
makes use of this class. An animated game object may contain a number of different
animations, so we can have a character that can perform different (animated) actions
such as walking, running, jumping, and more. Each action is represented by an
animation. Depending on the player input, we change the animation that is currently
playing. We will define a class called
AnimatedGameObject
which is a subclass of
SpriteGameObject
.