Moving your character with Root Motion and Blend Trees

The Mecanim animation system is capable of applying Root Motion to characters. In other words, it actually moves the character according to the animation clip, as opposed to arbitrarily translating the character model while playing an in-place animation cycle. This makes most Mixamo animation clips perfect for use with Mecanim.

Another new feature for the animation system is Blend Trees, which can make transitions between animation states smooth and easy. In this recipe, we will take advantage of these new features to make our character walk and run forwards or backwards, and also strafe right and left, at different speeds.

Getting ready

For this recipe, we have prepared a project named MixamoProject, containing several assets such as levels, animated characters, and props. You can find it inside the 0423_05_codes folder.

How to do it...

To apply Root Motion to your character using Blend Trees, perform the following steps:

  1. Open the project, and then open the level named 05_02 (inside the Levels folder). Note that it includes a S.W.A.T. character that features the Animator component using the swatController02 Controller.
  2. We need to configure our animation clips. From the Original_Character folder, select the Swat@rifle_run file.
  3. Click on the Rig tab. Change Animation Type to Humanoid and Avatar Definition to Copy From Other Avatar. Then, select swatAvatar for Source by choosing it from the list or dragging it from the Project view into the slot. Confirm your changes by clicking on Apply.
    How to do it...
  4. Now click on the Animations tab. Select the clip rifle_run (from the Clips list) and select the Loop Pose option. Under Root Transform Rotation, check Bake into Pose and set Body Orientation for Baked Upon (at Start); Under Root Transform Position (Y), check Bake into Pose and set Original for Baked Upon (at Start); Under Root Transform Position (XZ), leave the Bake into Pose checkbox deselected. Finally, click on the Clamp Range button to adjust the timeline (shown in the following screenshot). Click on Apply to confirm changes.
    How to do it...
  5. Repeat steps 3 and 4 for each one of the following animation clips inside the Original_Character folder: Swat@run_backwards, Swat@strafe, Swat@strafe_2, Swat@strafe_left, Swat@strafe_right, Swat@walking, and Swat@walking_backwards.
  6. From the Hierarchy view, select the Swat game object and attach a Character Controller component to it by going to Component | Physics | Character Controller. Then, set the following coordinates for Center: (0, 0.9, 0); change the entry in the Radius field to 0.34 and the Height field to 1.79:
    How to do it...
  7. In the Project view, open the swatController02 Controller.
  8. In the bottom-left corner of the Animator view, create three new parameters (Float values) named xSpeed, zSpeed, and Speed.
  9. Also, right-click on the gridded area and, from the context menu, select From New Blend Tree under Create State. Change its name to Move in the Inspector view.
    How to do it...
  10. Double-click on the Move state. You will see the empty Blend Tree you have created. Select it and rename it to Move in the Inspector view.
  11. In the Inspector view, below the diagram on the top, leave the parameter in the drop-down menu as xSpeed, but change the parameter values to -1 and 1. Also, use the button with the + sign to add three new Blend Trees. From top to bottom, rename them as StrafeLeft, WalkRun, and StrafeRight.
    How to do it...
  12. Select the WalkRun node. In the Inspector view, change the parameter to zSpeed. Then, change the parameter values to -2 and 2, and use the button with the + sign to add five Motion fields.
    How to do it...
  13. Now, fill the Motion list with the following clips (from top to bottom): run_backwards, walking_backwards, rifle_aiming_idle, walking, and rifle_run. You can do this either by selecting them from the list, or if there is more than one clip with the same name, dragging them from the Project view into the slot (by expanding the appropriate model icon).
    How to do it...
  14. Select the StrafeLeft node. In the Inspector view, keep its parameter as xSpeed but change the parameter values to -2 and 0; use the button with the + sign to add three Motion fields.
  15. Fill the Motion list with the following clips (from top to bottom): strafe, strafe_left, and rifle_aiming_idle.
    How to do it...
  16. Select the StrafeRight node. In the Inspector view, keep its parameter as xSpeed but change the parameter values to 0 and 2; use the button with the + sign to add three Motion fields.
  17. Fill the Motion list with the following clips (from top to bottom): rifle_aiming_idle, strafe_right, and strafe_2.
    How to do it...
  18. Let's go back to the base layer. In the Animator view, double-click on the gridded area or click on the Base Layer tab.
    How to do it...
  19. Right-click on the Idle state box and select Make Transition from the menu. Then, drag the white arrow into the Move box.
    How to do it...
  20. Select the arrow (it should turn blue). In the Inspector view, we can now configure the conditions that determine when and how the transition from Idle to Move is made.
  21. In the Conditions box, select the options Speed, Greater, and 0.1. Then, expand the BlendTree Parameters section, change zSpeed to 2 and click on the play icon in the Preview window. That should give you an idea on how the transition will be made.
    How to do it...

    Note

    You can experiment with narrowing and widening the blue segment of the timeline by using the handles to get a smoother transition.

  22. Now create a transition from the Move box to the Idle box. Then, select the arrow representing it.
  23. In the Conditions box, change the parameters to Speed, Less, and 0.1 (as shown in the following screenshot):
    How to do it...
  24. Now that we have established our animation states and transitions, we must create the script that will actually transform the player's input into those variables created to control the animation.
  25. From the Project view, create a new C# script and name it BasicController02.
  26. Open your script and replace everything with the following code:
    using UnityEngine;
    using System.Collections;
    
    public class BasicController02 : MonoBehaviour {
        private Animator animator;
        private CharacterController controller;
        public float transitionTime = 0.25f;
    
        void Start () {
            controller = GetComponent<CharacterController>();
            animator = GetComponent<Animator>();
            if(animator.layerCount >= 2)
                animator.SetLayerWeight(1, 1);
        }
    
        void Update () {
            float accelerator = 1.0f;
            if(controller.isGrounded){
                if (Input.GetKey (KeyCode.RightShift) ||Input.GetKey (KeyCode.LeftShift) ){
                    accelerator = 2.0f;
                } else if(Input.GetKey (KeyCode.RightAlt) ||Input.GetKey (KeyCode.LeftAlt) ){
                    accelerator = 1.5f;
                } else {
                    accelerator = 1.0f;
                }
                float h = Input.GetAxis("Horizontal");
                float v = Input.GetAxis("Vertical");
                float xSpeed = h * accelerator;
                float zSpeed = v * accelerator;
                animator.SetFloat("xSpeed", xSpeed, transitionTime, Time.deltaTime);
                animator.SetFloat("zSpeed", zSpeed, transitionTime, Time.deltaTime);
                animator.SetFloat("Speed", Mathf.Sqrt(h*h+v*v), transitionTime, Time.deltaTime);
                //transform.Rotate(Vector3.up * (Time.deltaTime * v * Input.GetAxis("Mouse X") * 90), Space.World);
            }
        }
    }
  27. Save your script and attach it to the Swat game object in the Hierarchy view.
  28. Play your scene and test the game. You should be able to control your character with the arrow keys (or the W, A, S, and D keys). You should also be able to get your character to run by pressing the Shift key or walk faster by pressing Alt.

How it works...

Our script will detect the user's keyboard input and translate it into variables to be passed to the Animator Controller as its parameters Speed, xSpeed, and vSpeed. These parameters will determine which animation clips should be played. For instance, if the player presses the down arrow and Shift keys together, the parameters Speed, xSpeed, and vSpeed will be passed with the values 1, 0, and -2 respectively. A positive value for Speed will trigger the transition from the Idle state to the Move state. Furthermore, an xSpeed value of 0, indicating that the left and right arrow keys are not being pressed, will favor the WalkRun Blend Tree and not StrafeLeft and StrafeRight. Finally, the vSpeed parameter (with a value of -2) will play the walking_backwards motion clip within the WalkRun Blend Tree. The character will then move according to the animation being played. Observe how pressing the Alt key actually blends the animation clips for walking and running in real time.

There's more...

If you want to learn more about Mecanim's animation system, there are some links you might want to check out, such as Unity's documentation at http://docs.unity3d.com/Documentation/Manual/MecanimAnimationSystem.html.

You can also check out Mecanim Example Scenes, available at the Unity Asset Store at http://u3d.as/content/unity-technologies/mecanim-example-scenes/3Bs and the Mecanim video tutorials, at http://video.unity3d.com/video/7362044/unity-40-mecanim-animation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.182.73