Game Development Reference
In-Depth Information
In order to store the different animations, we will use a
Dictionary
object. This
way, we can easily select another animation by looking through the dictionary and
choosing the appropriate animation based on an ID. The dictionary is declared as a
member variable in the
AnimatedGameObject
class.
protected
Dictionary<
string
,Animation> animations;
We also add two methods to the class:
LoadAnimation
and
PlayAnimation
. The first
method creates an
Animation
object and adds it to the dictionary:
Animation anim =
new
Animation(assetname, looping, frametime);
animations[id] = anim;
The
AnimatedGameObject
class is a subclass of
SpriteGameObject
. That means that
when this object is drawn on the screen, it will try to draw the sprite sheet that the
member variable
sprite
points to. However, note that the
AnimatedGameObject
class
has the following constructor:
public
AnimatedGameObject(
int
layer = 0,
string
id = "")
:
base
("", layer, id)
{
animations =
new
Dictionary<
string
, Animation>();
}
Because we pass along the empty string to the base constructor, the
sprite
variable
will contain the value
null
. What we need to do is assign the currently running an-
imation to the
sprite
member variable, so that this animation is then drawn on the
screen. We can easily do this, since the
Animation
class is a subclass of
SpriteSheet
,
which is also the type of the
sprite
member variable. We do this in the
PlayAnimation
method.
In that method, we first check if the animation we want to play is already playing.
If that is the case, we do not have to do anything else and we can return from the
method:
if
(sprite == animations[id])
return
;
Next, we check if we should copy the current mirror information, so that the newly
assigned animation will have the same mirrored state:
if
(sprite !=
null
)
animations[id].Mirror = sprite.Mirror;
Then, we call the
Play
method on the animation, so that the animation is initialized
and reset to the first frame:
animations[id].Play();