Let's add the ability to crouch when the dwarf is idle. The crouch animation is split up into two parts: the transition from stand to crouch, and the looping animation while crouching.
- In the idle state, if the user presses the space bar, set the crouch animation elapsed time to zero, make it non looping, and subscribe to the AnimationEnded event. This event only fires when an animation is set as non looping. You can subscribe to an event by pressing += and then pressing tab twice:
// Add this in the if (state=="idle") block of the UpdateState method
if (keyState.IsKeyDown(Keys.Space))
{
crouch.ElapsedTime = 0;
crouch.IsLooping = false;
crouch.AnimationEnded += new AnimationEventHandler(crouch_AnimationEnded);
state = "crouchDown";
}
- Scroll down to the crouch_AnimationEnded method that was created by Visual Studio's autocomplete. This is fired when the animation ends. When it fires, set the state to stayCrouched and unhook the event:
// Add this in the crouch_AnimationEnded method
state = "stayCrouched";
crouch.AnimationEnded -= crouch_AnimationEnded;
- Now add the crouchDown and stayCrouched states, which just set the animations for the bones:
// Add this in the UpdateState method
else if (state == "crouchDown")
{
RunController(dwarfAnimator, crouch);
}
else if (state == "stayCrouched")
{
RunController(dwarfAnimator, stayCrouched);
}
- At this point, we need to allow the dwarf to stand back up. However, the dwarf has no stand up animation. You can make him stand up by just changing the animation back to idle or blending between crouch and idle. Or, you can do it by running the crouchDown animation backwards. The last option will be covered in the next tutorial section.