Objective: Add movement animations to the Player when pressing either the left or right arrows.
Step 1: In Unity, with the Player GameObject selected in the Hierarchy window, create an animation file for the left turn and another animation file for the right turn using the chopped-up Sprite animation images from FileBase.
Save the .anim files in the Animations folder which is located inside the Assets folder.
Press the record button, and drag the Sprites onto the Dopesheet.
This will also add an Animator component to the Player, as seen in the Inspector window.
Step 2: Select both left and right animations in the Animations folder in the Project window and set the Loop Time to false.
Step 3: In the Player script, create a private variable of type Animator called _movementAnim and utilize [SerializeField].
Step 4: Go back into Unity, select the Player GameObject in the Hierarchy window, and drag the Animator component in the Inspector window into the Movement Anim slot in the Player (Script) component.
Step 5: In the Animator window, create an Empty state that the animations will loop back to for reset. Next, duplicate the left and right animation states by copy and pasting, and rename the states to something more descriptive.
In this instance, when the trigger key is pressed down, the initial animation state will play the original turn animation, and once the trigger key is released, the duplicate animation state will play the animation in reverse, simulating a return to the standard Player image. To accomplish this, create transitions from the Empty state to the Turn Left state, then from the Turn Left state to the Left To Center state, and then back to the Empty state. Do the same to the Right Turn states.
To reverse playback on the duplicate states, set the Speed of the duplicate states to -1.
Step 6: Create four trigger parameters, one for each transition to the animations.
In the Settings section in the Inspector window for each of these four transitions, set Has Exit Time to false and set the Transition Duration (s) to 0. This will eliminate any delay when triggering the animation.
Step 7: In the Player script, within the CalculateMovement() method, add if and if else statements to trigger each animation (left movement is red, right movement is green). So, if the left arrow key is pressed down, call the “LeftTurn” parameter to trigger the Left Turn animation. Then, when the left arrow key is released, call the “LeftTurnCenter” parameter to trigger the reversed animation. Then do the same for the right arrow key to trigger the Right Turn animations.
Save the script, go back into Unity, and now the Player tilts when moving to the left and right.