Game Development Reference
In-Depth Information
using
Microsoft.Xna.Framework;
1
using
Microsoft.Xna.Framework.Input;
2
3
4
class
Player : AnimatedGameObject
{
5
public
Player() :
base
(0, "player")
6
{
7
this
.LoadAnimation("Sprites/Player/spr_idle", "idle",
true
);
8
this
.LoadAnimation("Sprites/Player/spr_run@13", "run",
true
);
9
}
10
11
12
public override void
HandleInput(InputHelper inputHelper)
{
13
velocity.X = 0.0f;
14
if
(inputHelper.IsKeyDown(Keys.Left))
15
−
velocity.X =
400;
16
else if
(inputHelper.IsKeyDown(Keys.Right))
17
velocity.X = 400;
18
}
19
20
21
public override void
Update(GameTime gameTime)
{
22
if
(velocity.X == 0)
23
this
.PlayAnimation("idle");
24
else
25
this
.PlayAnimation("run");
26
Mirror = velocity.X < 0;
27
base
.Update(gameTime);
28
}
29
}
30
Listing 26.2
A class for the player character
If the player character is walking in the left direction (e.g., the velocity is nega-
tive), we have to mirror the animation. We can write this down neatly in a single
instruction using some boolean logic:
Mirror = velocity.X < 0;
The right-hand side of this instruction yields
true
if the character is walking in the
left direction, and
false
if the character walks in the right direction. The value of
this expression is set to the
Mirror
property, which leads exactly to the behavior that
we want. Finally, we call the
Update
method in the base class, to make sure that the
animation game object version of the
Update
method is called as well.