Roll animation in Unity
Objective: Add in a roll animation to the player controller in Unity
The last part to this project was adding a roll animation for the player. I first went to Mixamo and found an animation that I liked that is a running to roll animation.
I downloaded and imported it to the project and then followed the same procedure as the other animations. Once the animation is set up in the animator, along with the transitions and parameters to activate the animation.
Before I show the code I am using, I will say that I was having issues with the roll animation due to the character controllers capsule collider. When rolling the players capsule is still the same height, so if the player is rolling under a platform to get through a section, they would collide with the box. I had to find away to shrink the collider when rolling and then set it back again once the roll animation has finished.
The issue I was having was fixed with the above code. I am changing the height of the collider to 0 and then setting a new center, so that the player doesn’t fall through the floor until they collide with the collider.
In the clip above I hope you can see the collider is changing height when rolling and then going back once the roll has finished.
Following on from my previous animation article where I went through how to add an animation behaviour, I did the same for this animation.
The code above is called once the roll animation is completed. But how do you know when the animation has finished? Well, if you click on the animation in question in the animator, you will see in the inspector an option to add a behaviour.
I’ve already added my behaviour but all you need to do is click the add behaviour button and create the script. This is not a normal script, as you cannot add in extra mono behaviours.
You will see some override methods that are all commented out. Find the method for OnStateExit and uncomment the code. This gives you access to the animator component for the object. For me, my PlayerController script is on the parent object to where the animator component is found.
I am grabbing the PlayerController component and then calling the method I showed earlier.
And that is it for adding in the roll animation to my character controller.