Getting Started
- First, to organize things, create a new method UpdateState(GameTime time) and call it at the beginning of update.
// Add this as a new method
private void UpdateState(GameTime gameTime)
{
}
// Add this to the beginning of the Update method
UpdateState(gameTime);
- Add the following member variables:
// Add these as member variables
// This represents what the dwarf is doing
string state = "idle";
float currentSpeed = 0;
const float WALK_SPEED = .115f;
Rotating the Dwarf
- Regardless of what the dwarf is doing, we want the user to be able rotate him using "A" and "D". Add this code to the Update method:
// Add this to the beginning of the Update method
KeyboardState keyState = Keyboard.GetState();
if (currentSpeed > 0)
{
dwarfPosition += (-Matrix.CreateTranslation(0, 0, currentSpeed)
* rotation).Translation;
}
if (keyState.IsKeyDown(Keys.D))
{
rotation *=
Matrix.CreateFromAxisAngle(Vector3.Up, -MathHelper.Pi / 25.0f);
}
if (keyState.IsKeyDown(Keys.A))
{
rotation *=
Matrix.CreateFromAxisAngle(Vector3.Up, MathHelper.Pi / 25.0f);
}
- When we increment the dwarfs position, we move him forward in the direction he is facing. This is calculated by reversing the "normal" order of matrix multiplications and doing (translation * rotation).
Moving the Dwarf when he Walks
- Now add this code to the UpdateState method:
// Add this to the UpdateState method
KeyboardState keyState = Keyboard.GetState();
BonePoseCollection poses = dwarfAnimator.BonePoses;
if (state == "idle")
{
currentSpeed = 0;
if (keyState.IsKeyDown(Keys.W))
state = "walk";
RunController(dwarfAnimator, idle);
}
else if (state == "walk")
{
currentSpeed = WALK_SPEED;
if (keyState.IsKeyUp(Keys.W))
state = "idle";
RunController(dwarfAnimator, walk);
}
- "W" tells the dwarf to walk, and releasing "W" makes him idle.
- If the dwarf is idling, we set the current animation to idle.
- The blend animation, if not null, determines what animation that the current animation will be blended with.
- You will notice that the transition between idle and walk is unconvincing. This can be fixed with animation blending, which will be described in the next section.