Game Development Reference
In-Depth Information
Now that the preparatory work is done, we assign the current animation to the
sprite
member variable:
sprite = animations[id];
Finally, we also change the origin of the animated game object. If we want to draw
animated characters moving on the floor, then it would be much more useful to use
a point on the
bottom
of the character sprite as its origin. Also, as we will see later
on, this is useful for collision checking. For these reasons, we are going to define
the origin of the animated game object as the point in the middle of the bottom of
the sprite element:
origin =
new
Vector2(sprite.Width / 2, sprite.Height);
Finally, the
Update
method of the
AnimatedGameObject
class calls the
Update
method on the currently selected animation. For the complete
AnimatedGameObject
class, see Listing
26.1
.
26.6 The
Player
Class
In order to use the
AnimatedGameObject
class introduced in the previous section, we
inherit from it. Since the player will control the animated character, let us define a
Player
class that is a subclass of the
AnimatedGameObject
class. Within this class, we
load the animations belonging to the player, and handle the input from the player.
The full
Player
class is shown in Listing
26.2
. In the constructor of the
Player
class,
we load the animations that are needed for this character. In this example, we want
the character to walk or stand still. So, we load two animations and add them to the
dictionary by calling the
LoadAnimation
method. We want both of these animations
to loop, so we set the looping parameter to
true
:
this
.LoadAnimation("Sprites/Player/spr_idle", "idle",
true
);
this
.LoadAnimation("Sprites/Player/spr_run@13", "run",
true
);
Now we need to handle the input of the player in this class. When the player presses
the left or right arrow key, the velocity of the character should change. We do this
in the
HandleInput
method using an
if
-instruction (see Listing
26.2
).
In the
Update
method, we select which animation to play based on the veloc-
ity. If the velocity is zero, we play the idle animation, otherwise we play the 'run'
animation:
if
(velocity.X == 0)
this
.PlayAnimation("idle");
else
this
.PlayAnimation("run");