Add Animation to Player Movement

Tristan Engel
3 min readSep 17, 2021

--

In this article we will animate our player when walking. We got our place holder player moving with our movement system. Let’s replace it by the final model and add the walk animation to it.

Placeholder to Player Model

Transform Scale set to 1, 1, 1
Hide Mesh Renderer

Drag in Player Model into Player GameObject so it becomes a child
Adjust the Capsule collider so it matches the new model

Let’s move around.

Setup Animator for Player Walk Animation

Create Animator Controller
Attach Animator to Player
Open Animator and drag in Idle animation and drag in other animations.

R-click Idle > Make Transition > Click Walk
R-click Walk > Make Transition > Click Idle

Select a Transition Arrow > in the Inspector turn off Exit time
Do this for on both transitions. Exit Time means the animations will finish playing first then start the other animation.

Animator > Parameters (tab) > + > Bool > Rename to Walk

Select Transition Arrow > Inspector > Conditions > +
Do this for on both transitions. Set up when the animation should transition to the other animation. When walk becomes true or false.

Control Animation from Code

To control the animation from code we need to modify the bool Walk variable from the animator.

When we L-click we change the Animation Bool Walk to true.
If the player position is equal to the destination to move to we change the Animation Bool Walk to false.

//handle
private NavMeshAgent _agent;
[SerializeField] private Animator _animator;


void Start ()
{
_agent = GetComponent<NavMeshAgent>();
_animator.SetBool("Walk", false);
}

void Update ()
{
if (Input.GetMouseButtonDown(0))
{
_animator.SetBool("Walk", true);

RaycastHit hitInfo;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hitInfo))
{
_agent.destination = hitInfo.point;
}
}
if (transform.position.x == _agent.destination.x && transform.position.z == _agent.destination.z)
{
_animator.SetBool("Walk", false);
}

}

Alternative: Check by Distance

Another way to check if destination is reached by the player is to check for the distance. Often variables are floats and tiny differences are possible which causes things to behave unexpectedly.

Replace the transform.position if statement with the code below.

float distance = Vector3.Distance(transform.position, _agent.destination);
if (distance <= 1f)
{
_animator.SetBool("Walk", false);
}

Tweaking how the Nav Mesh Agent moves

In the Inspector we can tweak numbers on how our Nav Mesh Agent moves. Things like speed, acceleration, stopping distance etc.

--

--

Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.