Day 87 — Implementing Animations: Running Animation
Hey and welcome!
Let’s look into adding in the running animation next. Go ahead and drag and drop that in the animator window and right click it to make a transition that you can attach to your idle animation there. Make a second transition from your idle to running animation as well.
In order to make use of these transitions we’ll need a parameter for them that they need to look out for, create a new float parameter called Speed and you should end with something like this so far:
If you click on the transition arrow you’ll see an option in the inspector to add a condition to it, for your transition from running to idle set a condition where the speed is less than 0.1.
Then for the other transition set the condition to be when speed is greater than 0.1.
There’s also an option here for Exit Time, make sure you uncheck that so that the animations can transition immediately when the condition is met.
This doesn’t do too much good for us currently though, if you run the game now you’ll find that it’s not switching back and forth so we’ll need to modify the code in the Player script a little to get things rolling.
private Animator _anim;void Start()
_anim = GetComponentInChildren<Animator>();
if (_controller.isGrounded == true)
float horizontalInput = Input.GetAxis("Horizontal");_anim.SetFloat("Speed", Mathf.Abs(horizontalInput));
I’ve just kept in the important stuff this time round. We start things off by caching a reference to the Animator component using GetComponentInChildren since the Animator is on our model that’s a child of the Player object.
In the Update method we’re using _anim.SetFloat() in order to change the value of our Speed parameter in the animator and this is what’s going to cause the state to change from idle to running or vice versa. If you remember, Input.GetAxis(“Horizontal”) returns a float between -1 and 1 so we can pass that in as the value we set.
If you had it just as that though you’d notice that your character doesn’t play the running animation when running to the left since -1 is less than 0.1. To fix that we use Math.Abs() which returns the absolute value of the number. That means that -0.5 would become 0.5 which makes it greater than 0.1 and lets the running animation play.
Looking pretty good apart from the character not turning around when running to the left, we’ll get that fixed after we add in the jump animation.