On a Roll! — Player Roll Animation
We will change the Character Controller Collider through code when entering a roll to match the changed profile of the model and then change it back to normal after the animation.
In the Player script, we need some variables to implement the roll logic.
- The amount to add to the Player’s velocity when rolling.
- The new XYZ axis values for the Collider’s Center when rolling.
- The starting XYZ axis values for the Collider’s Center to return to after rolling.
- The new Height value for the Collider when rolling.
- The starting Height value for the Collider to return to after rolling.
- The bool to know if the Player is already rolling, to prevent jumping and rolling while rolling.
We get the starting values for the Collider’s Center and Height from the Controller in Start.
While the Player is on the ground, if the Left Shift key is pressed and not already rolling, we tell the Animator to play the roll animation, disable rolling and jumping till the roll is finished, and change the Collider’s Center and Height to the smaller profile. Then if the Player is rolling, we add or subtract the roll force from the velocity depending on which direction the Player is facing.
The last thing we need is a method that can be called to change the rolling bool to false enabling jumping and to roll again and to return the Collider’s Center and Height to the starting values.
In the Animator window for the Player, we need to add a Trigger Parameter for Roll to Transition to the rolling animation. Then after the animation has finished, we Transition back to Idle or Run animations. On the Roll animation State, we need to add a Behaviour script.
In the Behaviour script, when the rolling animation State finishes and Transitions to the next State, we grab the PlayerController script from the parent of the Animator and call the Stop Roll method on it.
The Player can now roll and move under the obstacle.