2D Mobile Game: Player Run Animation Optimized
In this article, I will cover how to create a separate script that will handle all of the player animations and implement our already created run animation into this cleaner version.
We will start with creating a new script, PlayerAnimation, and attach it to the Player game object.
Create a variable to store the Animator component and complete a null check.
In the Player script, we will declare a variable that will hold the PlayerAnimation script and assign it in the OnStart. Complete a null check to ensure we have access to the PlayerAnimation script.
Back in the Player Animation script, we are going to create a method that will handle the animation transition between Idle and Run. This method will need to be accessed by the Player script since we are using the horizontalInput value from that to meet the animation transition condition, so we need to make it a public method. Again, since we are using the horizontalInput value from the Player scrip, we are going to need a float parameter, horizontalInput, so we can pass that in when calling it. We access the Animator and set the Move animator parameter to the absolute value of the horizontalInput.
Now that the Move method has bet setup, we will need to make use of it by calling it in the Player script. We can call the Move method via the _playerAnim variable and we will pass in the horizontalInput value that determines if we are moving.
The last thing we need to include is the sprite flip when moving left and right. We are moving this into a private method in the Player script and will accept a float parameter called horizontalInput. Again, the horizontal innput value determines what direction is moving in, so we need it to know when to flip it facing left and flip it facing right.
I renamed the SpriteRenderer variable from _spriteRenderer to _playerSprite. This variable is storing the SpriteRenderer of the player and gives us access to the flip method.
If the horizontal input is less than 0 the player is moving left, so we set the flip to true and if it is greater than 0 the player is moving right, we set the flip to false.
Lets make use of the Flip method by calling it after we store the horizontal input and pass it into the Flip method. This will take care of flipping the sprite image in the direction it is moving.