You are here:   Blog
Register   |  Login

Unity Character Movement Animation and Blend Trees

Nov 28

Written by:
11/28/2015 11:05 AM  RssIcon

image

Unity provides several options to allow the user to control a character. The most realistic involve animation and Blend Trees.

We will explore the various options, and create the sample program available at the following link:

http://adefwebserver.com/unity/testjumpgame/ (requires Chrome/Firefox/ or Microsoft Edge web browsers).

image

To control the player, you use the arrow keys. However, if you click the down arrow key, nothing happens. You have to hold down the right or the left arrow keys, so that you are walking first.

image

When you do this, the character will walk in a crouching stance.

image

When you hold the up arrow key down while walking forward, the character will walk above the ground.

image

This is required because otherwise the character will fall to his death when crossing the gaps in the floor.

image

Finally, to demonstrate that we have programmatic control, the player earns one point for crossing past the halfway mark and another point for reaching near the end of the right-hand side of the screen.

Easy Animated Character Controller

image

You can actually create an animated movable character in a few easy steps. 

image

Create a new 3D Unity project (see: Unity 5 Hello World! for instructions on how to do this).

When it opens, ensure that you have Default layout selected.

image

From the menu bar, select GameObject, 3D Object, then Plane.

image

A plane will be added to the scene.

image

Next, from the menu bar, select Assets, Import Package, then Characters.

image

When the Import dialog shows, click the Import button.

image

After the import is complete, the folders and items can be found in the Assets folder.

Navigate to the Standard Assets/Characters/ThirdPersonChracter/Prefabs folder and drag the ThirdPersonController prefab to the design surface.

(note: a Prefab is a container that contains multiple elements (also contained in the other folders) such as a model, animations, and scripts)

image

When you click the Play button, you will have the ability to use the keypad to move the character around on the plane.

image

Click the Play button to stop the game.

Select the Scene tab so that you can edit the scene.

Select the character, and in the Properties double-click on the Controller under the Animator section.

image

This will open the Animator tab and display the state machine in the animation controller window.

(note: you can move the contents around by clicking on the gray design area, holding down the center mouse button, and moving the mouse)

image

If you double-click on the Grounded state…

image

It will display the Blend Tree and provide access to the animations that add visual life to the avatar.

Simple Character Movement

image

To learn how character control, animation and Blend Trees work, we will create a project from scratch and slowly build it up in complexity.

First, create a New Scene.

image

Change it to 2D by clicking the 2D button.

Add a Plane to the scene using the following settings:

image

To change the Mesh Collider Material to Ice, click on the round selector to the right of the Material box and select Ice from the popup.

image

In the Hierarchy, select the Main Camera.

Set it to the following settings:

image

To set the Camera Background

image

… click the Background color bar to open the Color popup.

image

Enter: 314D7905

Close the popup.

image

When you run the project you will see a simple stage.

Stop the game.

image

Add a Cube.

Use the following settings:

image

Note that we have  Box Collider attached to the object so that it will interact with other objects…

image

However, when we run the project, the Cube hangs in midair over the Plane.

Stop running the project.

image

At the bottom of the Inspector for the Cube, press the Add Component button.

image

Select Physics.

image

Then select Rigidbody.

image

The Rigidbody component will be added to the Cube.

image

When you run the project, the Cube will now fall and drop to the Plane.

image

Return to the project, and select the Cube in the Hierarchy.

In the Inspector for the Cube, press the Add Component button and then select New Script.

image

Enter MoveRigidBody for the Name, ensure C Sharp is selected for the language, and click the Create and Add button.

image

The MoveRigidBody script will be created (It will also display in the Assets folder).

The script will also be attached to the Cube.

Double-click on the MoveRigidBody script to open it.

image

The script editor will open.

Replace all the code with the following code:

 

using UnityEngine;
using System.Collections;
public class MoveRigidBody : MonoBehaviour {
    public float MoveSpeed;
    private float HorizontalMove;
    private float VerticalMove;
    private Rigidbody Box;
    // Use this for initialization
    void Start()
    {
        // Get a reference to the object this script
        // is attached to.
        Box = GetComponent<Rigidbody>();
    }
    // Update is called once per frame
    void Update()
    {
        // Get Horizontal movement
        HorizontalMove = Input.GetAxis("Horizontal");
        // Get Vertical movement
        VerticalMove = Input.GetAxis("Vertical");
        // Ensure there is movement
        if (HorizontalMove != 0 || VerticalMove != 0)
        {
            // Move the Cube
            Box.velocity = 
                new Vector2(
                    (HorizontalMove * MoveSpeed),
                    (VerticalMove * MoveSpeed));
        }
    }
}

 

image

Save the code.

image

Switch back to the Unity editor.

Enter 5 for the Move Speed, and then run the game.

You will be able to move the Cube around using the arrow keys.

Moving An Avatar

image

In the Hierarchy, right-click on the Cube and select Delete (to delete it).

image

In the Project window, select the Assets folder, then navigate to:

Standard Assets > Characters > ThirdPersonController > Models

(these assets were added when we imported the Characters package).

Drag and drop the Ethan prefab onto the design surface (it will also show in the Hierarchy)

image

Use the Add Component button to add a Rigidbody (Physics > RigidBody) and a Capsule Collider (Physics > Capsule Collider) to the Avatar.

(note: the Animator component does not have a Controller configured (yet) so it will not do anything)

Set all the settings according to the image (above).

image

Select the the Add Component button, then select Scripts

image

Select the Move Rigid Body script (we created earlier).

image

Enter 5 for the Move Speed, and then run the game.

You will be able to move the Avatar around using the arrow keys.

Move The Avatar Using Animation

image

We will now introduce a different way of moving the Avatar using animation.

Click the Settings gear on the Move Rigid Body script and select Remove Component.

image

From the menu bar, select Assets, then Create, and Animator Controller.

image

The Animator Controller will appear in the Assets.

Click on it to rename it to AnimationController.

image

Click on Ethan in the Hierarchy so that its properties will display in the Inspector.

Drag and drop the AnimationController to the Controller property of the Animator component.

image

Switch to the Animator window (if it is not showing select Window from the menu bar then Animator)

Locate the Any State state and Entry state (by holding down the center mouse button and dragging on the gray grid).

When you locate them, right-click on the gray grid and select Create State then Empty.

image

The new state will appear.

image

Change the name of the state to Idle.

Click the selector to the right of the Motion property and select HumanoidIdle animation from the popup.

(these assets were added when we imported the Characters package).

image

Add a WalkRight state that uses the HumanoidWalk animation for the Motion.

image

To create a transition between the Idle animation and the WalkRight animation,

right-click on the Idle animation and then select Make Transition.

image

Then click on the WalkRight state.

image

A line with an arrow point to the WalkRight state will appear.

Repeat the process, in reverse (right-click on the WalkRight state first), to make a arrow pointing from the WalkRight state back to the Idle state.

image

Switch back to the Scene window, click on Ethan in the Hierarchy, and set its Transform properties according to the image above.

Run the project.

image

The Avatar will walk to the right…

image

… and fall to his death!

Triggering Animations

image

We will now alter the animation so that it is programmatically triggered.

Select the Animator window, then click on the Parameters section.

Click the + symbol in the Parameters section to create a new Trigger parameter.

image

Name the Trigger WalkRightTrigger.

image

Click on the transition from Idle to the WalkRight state.

The properties for the transition will appear in the Inspector.

Click on the + icon in the Conditions section to add a condition for the transition.

image

A new Condition will appear.

Use the dropdown selector to select the WalkRightTrigger for the condition.

image

Uncheck the Has Exit Time for the transition.

This will cause the transition to fire immediately when we trigger it.

image

Select the Scene window, and select the Ethan in the Hierarchy.

In the Inspector for Ethan, press the Add Component button and then select New Script.

image

Enter PlayAnimation for the Name, ensure C Sharp is selected for the Language, and click the Create and Add button.

image

The script component will be added to the Ethan properties.

Double-click on the PlayAnimation script to open it.

image

The script will open in the script editor.

Use the following code for the script:

 

using UnityEngine;
using System.Collections;
public class PlayAnimation : MonoBehaviour
{
    private Animator objAnimator;
    // Use this for initialization
    void Start()
    {
        objAnimator = GetComponent<Animator>();
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("right"))
        {
            objAnimator.SetTrigger("WalkRightTrigger");
        }
    }
}

image

Save the script and return to the Unity designer.

When we press the right arrow key, the Avatar will move.

image

Stop the game and return to the Animator window.

Create a new Trigger named WalkLeftTrigger.

Create a new state called WalkLeft and set the animation to HumanoidWalk.

Set the Speed to –1 so that the animation will play backwards, and cause the Avatar to walk to the left.

image

Create transitions to and from the WalkLeft state to the Idle state.

Select the transition from the Idle state to the WalkLeft state and add a condition that uses the WalkLeftTrigger.

Uncheck the box next to Has Exit Time.

Add the following code to the Update() method of the PlayAnimation script:

 

        if (Input.GetKeyDown("left"))
        {
            objAnimator.SetTrigger("WalkLeftTrigger");
        }

 

image

When we run the game, the Avatar will walk backwards when we press the left arrow key.

Using Blend Trees

image

We will now use Blend Trees to allow the character to jump and crouch while walking, and to smoothly transition between the states, and in some cases operate in more than one state at a time.

image

First, open the Animator window, select Parameters, and right-click on each trigger, and delete both Parameters.

image

Also, right-click on the WalkLeft and WalkRight states and delete them.

image

Add a Float parameter.

image

Name the parameter inputH.

Add another Float parameter and name it inputV.

These will tract the Horizontal and Vertical controls for the Avatar.

image

Right-click on the gray grid and select Create State then From New Blend Tree.

image

Name the state Walk Left (Blend Tree).

Add another and name it Walk Right (Blend Tree).

Add Transitions for each state, to and from the Idle state.

image

Click on the Transition from the Idle state to the Walk Left (Blend Tree) state and add a Condition that inputH be Less than –0.1. Also uncheck the Has Exit Time box.

image

Click on the Transition from the Walk Left (Blend Tree) state to the Idle state and add a Condition that inputH be Greater than –0.1.

image

Click on the Transition from the Idle state to the Walk Right (Blend Tree) state and add a Condition that inputH be Greater than 0.1. Also uncheck the Has Exit Time box.

image

Click on the Transition from the Walk Right (Blend Tree) state to the Idle state and add a Condition that inputH be Less than 0.1.

image

Double-click on the Walk Left (Blend Tree) state.

image

This will open up the Blend Tree for the state.

Set the Blend Type to 2D Simple Directional.

Set inputH and inputV for the Parameters.

Click the + icon under Motion and select Add Motion Field.

image

Set the Pos X and Pos Y to the settings the image above.

Set each motion to the setting in the image above by selecting the selector for each line and selecting the animation from the popup window.

image

You now have a Blend Tree.

Click Base Layer in the upper left to go back.

image

Next, double-click on the Walk Right (Blend Tree) state to edit it.

image

Enter the settings according to the image above.

Click Base Layer in the upper left to go back.

image

Switch to the Scene window, click on Ethan in the Hierarchy, and in the Inspector, double-click on the PlayAnimation script to open it.

Use the following code for the script:

 

using UnityEngine;
using System.Collections;
public class PlayAnimation : MonoBehaviour
{
    private Animator objAnimator;
    private Rigidbody objRigidbody;
    private float inputHoriontal;
    private float inputVertical;
    // Use this for initialization
    void Start()
    {
        // Get a reference to the object this script
        // is attached to.
        objAnimator = GetComponent<Animator>();
        objRigidbody = GetComponent<Rigidbody>();
    }
    // Update is called once per frame
    void Update()
    {
        // Get Horizontal and Vertical input
        inputHoriontal = Input.GetAxis("Horizontal");
        inputVertical = Input.GetAxis("Vertical");
        // Pass the Horizontal and Vertical input
        // values to the Animator 
        objAnimator.SetFloat("inputH", inputHoriontal);
        objAnimator.SetFloat("inputV", inputVertical);
        // Are we facing Left?
        if (inputHoriontal <= -0.1)
        {
            // Turn the Avatar to the left
            transform.rotation = Quaternion.AngleAxis(-90, Vector3.up);
        }
        // Are we facing Right?
        if (inputHoriontal >= 0.1)
        {
            // Turn the Avatar to the right
            transform.rotation = Quaternion.AngleAxis(90, Vector3.up);
        }
    }
}

 

image

When we save the script and run the game we will be able to make the Avatar jump and crouch when he is moving forward.

Completing The Game

image

Stop the game, and in the Hierarchy, delete the Plane.

image

Click on the menu bar, select GameObject > 3D Object > Plane to add a Plane.

image

Add two more, so there is a total of three.

image

Set the settings for Plane1 according to the image above.

image

Set the settings for Plane2 according to the image above.

image

Set the settings for Plane3 according to the image above.

image

When we run the game, the Avatar can potentially fall between the gaps in the planes unless it is jumping or crouching wile walking.

Stop the game.

Add the following Using statement to the PlayAnimation script:

using UnityEngine.UI;

 

Also, and add the following code to the PlayAnimation script:

    public Text ScoreTextBox;
    private float intCurrentScore = 0F;

 

Also, and add the following code to Update() method of the PlayAnimation script:

        // Handle Score
        if(transform.position.x > 1 && intCurrentScore == 0)
        {
            intCurrentScore = 1;            
        }
        if (transform.position.x > 5 && intCurrentScore == 1)
        {
            intCurrentScore = 2;
        }
        ScoreTextBox.text = string.Format("Score: {0}", intCurrentScore);

 

image

When we save the script and switch back to the Unity editor, we see that there now a Source Text Box field.

We now need to create a label in the game and attach it to the box so the score will show.

image

Add a Text object.

 

image

It will show in the Hierarchy inside a Canvas.

image

Click on the Canvas element in the Hierarchy, and in the Inspector, set its settings according to the image above.

image

To set the Camera for the Canvas, click the selector next to Event Camera, select Main Camera, then close the popup box.

image

Click on the Text element in the Hierarchy, and in the Inspector, set its settings according to the image above.

image

Click on the Ethan element in the Hierarchy,

In the Inspector, click the selector next to Score Text Box, select Text, then close the popup box.

image

When we run the game, the Avatar will score two points when it moves to the right of the screen.

The game is now complete.

Links

Unity 5 Hello World!

Beginner Tutorial: A Unity 5 Number Guessing Game

Download

You can download the code from the Download page.

Unity 5 (or higher) is required to run the sample code.


Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel