Journal 96 — Unity 2D Mobile, Dungeon Escape Player Animations
Objective: Add the player animations for idle, run, and jump
In the previous article, I added the movement and jump behavior. In this article, I will go through adding the player animations.
The first animation to address is idle animation. We need to create a storage folder for the animations, and then create a new idle animation using the Animation window.
Now that we have the default state, let’s add the run animation using the same approach.
Before going further, you can adjust the animation speed in Game mode by reducing the speed from the Animator window.
We need to create the transitions with a float variable called “Move”. When Move is greater than 0.1, we will transition to running, and when Move is less than 0.1, we will switch back to idle.
We can create a new C# script called PlayerAnimation to handle all the animations.
In the Player script, we can get a reference to the PlayerAnimator script and pass in the horizontalInput value.
The SpriteRenderer component on the player sprite has a check box to Flip on the X and Y axis. When running left, the horizontalInput value is -1, so this should trigger the Flip X-axis. We can use a simple if-then condition to check the horizontalInput and trigger this change.
Here are the results.
Now let’s add the jump animation using the same process as above.
We can also set up the transitions for jumping when in an idle state. We can create a bool called “Jumping” and use this for the transitions.
Now let’s update the C# scripts.
We can make a new public void function to handle the jump animation in the PlayerAnimation script. We can pass in a true/false variable for when the player should jump.
In the Player script, we can reference this function when the space bar is hit to jump, and also when the grounded check is done. After some trial and error, the grounded check should be done constantly in the Move function.
Here are the results.
Let’s update the Animator to add a run jump transition.
After looking at the jump animation, we can simplify the animation to just a few specific frames.
We can go to the Animation window and delete the jump animation, and then drag these specific frames into the window. Then we can take the last frame and drag it to the right to lengthen the total animation to at least a second or longer. This will make it appear the player is jumping in the air over the jump distance before landing.
Let’s try this again in Play mode.
Thank you for your time!