- Mastering Unity 2D Game Development(Second Edition)
- Ashley Godbold Simon Jackson
- 3260字
- 2021-07-08 11:05:22
Animating the main character
Right now, our hero can move around the screen, but she is always facing toward the camera and she isn't animated. Her sprite sheet came with her walk cycle from three angles, so let's put that into action to liven up her movement.
We will accomplish this movement by creating some Animation clips and linking them up in an Animation controller. As described earlier, in order to get the animation running, we will need the following prerequisites:
- An Animator component on our GameObject
- An Animator Controller to manage our animation that is bound to the animator
- At least one Animation clip to play in the controller
When you create a new animation clip for a GameObject, the other items are automatically created for you.
Before you get started with animation, you want to make sure you can view the Animation and Animator windows. If you do not already have the two windows open, click Window | Animation from the menu bar and then Window | Animator.
Note
You may want to rearrange your windows at this point. I recommend docking the Animation and Animator windows next to the Game window so you can see the Project
folder while creating animations, as shown in the following screenshot:

This is easily done by dragging the tabs for the windows to the desired point. When it gets near a point in the editor where it can dock, it will do so automatically.
Adding your first Animation Clip
The animation we will create first will be that of our character walking downward. To create your first animation clip, select the Player from the Hierarchy (or from the Scene view) and then open the Animation tab. You should see the following:

Prompt to create Animator and Animation Clip
Select Create and then save the animation as PlayerWalkDown.anim
within your Assets/Animation/Clips
folder, as shown in the following screenshot:

Animation file save menu
By selecting Create, Unity will automatically create an Animator for your Player and will automatically assign it within an Animator component on the Player. However, it has saved the new Animator in the Clips
folder, as shown in the following screenshot:

Note
Notice that the generated Animator Controller is called Player.controller
. Any Animator that is automatically created in the way will always be named after the GameObject that was selected when it was created.
Go ahead and drag and drop that Animator into the Assets/Animation/Controllers
folder so that we maintain the integrity of the folder structure we created.
Within the Animation window, you should now see PlayerWalkDown within the drop-down menu, as shown in the following screenshot:

Within the Project view, navigate to the Assets/Sprites/Characters
folder to find the character's sprite sheet and click on the arrow on the right of the sprite sheet to view all of the character's walk cycle sprites. The first three images represent the character's downward walk cycle:

Character sprite sheet for downward walk cycle
Select all three of these images by clicking on the first image, holding down Shift, and then clicking on the third image. Now drag and drop these three images into the Animation window's Dope Sheet. You should now see the following:

Currently, this animation is way too fast. Clicking on the play button to play the game will demonstrate this. We will slow this character's animation by reducing the frame rate to 6 fps, by changing Samples from 60 to 6, as shown in the following screenshot:

Note
You can slow an animation in two ways: by adjusting the frame rate or by spacing the images further apart along the timeline. To move the images further apart, simply click and drag them to the frame you wish to place them.
Remember that 1:00 represents 1 second, not 1 minute.
Press Play to play the game. You will now see that the animation is running much more naturally.
Note
You can view the animation without running the game by pressing the play button within the Animation Window. However, to see this animation run, you will need to have both the animation and Scene windows open, and the window tab configuration we discussed earlier does not allow that. You can adjust the location of your various windows so that you can have both the animation and scene window present. I recommend experimenting with moving the various tabs around to see where they can be placed.
While the animation has a better speed, it is not complete. Even though only three frames are given for her downward walk cycle, you actually have to use the center image twice to make the walk animation loop perfectly. The following figure demonstrates the logic behind a three-frame walk cycle:

To make her animation complete, you must also have the second frame repeated at the end of the animation. So, place the Protagonist_1
sprite as the fourth frame in the animation, as shown in the following screenshot:

Your animation should now appear as follows:

Setting up the Animator and default state
Remember, when we created the PlayerWalkDown.anim
animation, an Animator Controller named Playercontroller
was automatically made for us. We moved it into the Assets/Animation/Controllers
folder. It was also automatically assigned to an Animator component in the Player's Inspector, as shown in the following screenshot:

Animator component in Player's Inspector
We are going the leave all of the default settings in the Animator component, but we will rename the Animator to make it easier to recognize later on. Let's rename our Animator as PlayerWalking.controller
(note that you do not have to type the .controller
extension). You can accomplish this by clicking on it twice slowly or pressing F2 on a keyboard:

Renaming Animator component
You will see that this name has been updated in the Player's Inspector, as shown in the following screenshot:

When you open the Animator window, you should see the following:

Note
Depending on how large your Animator window is, you may also see the red Exit state. Do not worry about that state at this time, as we will not be using it. Sometimes, when you have more than one animation controller, it can be difficult to tell which animator you are working on. Notice that it tells you that name of the controller you are working with at the bottom right-hand side of the Animator window.
The PlayerWalkDown.anim
animation has already been added to the Animator, and since it was the first animation we created, it has been designated the default state (as demonstrated by the fact that the animation is colored orange). When we begin our game, our character automatically starts walking downward, even when she is standing still. However, we want her to just face downward until we make her start walking. The reason she is animating initially is her default state is set to PlayerWalkDown.anim
.
Let's fix this by creating an empty default state. Right-click anywhere within the Animator Window and select Create State | Empty, as shown in the following screenshot:

Rename this from New State
to PlayerStandDown
. Then right-click on it and select Set as Layer Default State to make this Empty State be the new default state, as shown in the following screenshot:

You should now have an Animator that looks something like the following:

Animator window
Run your game and you will see that the player now no longer automatically animates. In fact, she no longer animates at all! To get her to animate only when she's walking, we're going to have to tell the controller how and when her animation needs to run. Before we do that, however, let's set up the other animations the character will need.
Adding the other Animation Clips
The character's sprite sheet had two other animations within it that we will need to set up to let our character convincingly walk around the screen: walking to the right and walking upward.
Note
If you're wondering why we do not have a left walking animation, we will use the walking to the right frames to animate our character going both left and right.
Navigate back to the Animation window for the player. Now we will select Create New Clip from the animation selection drop-down menu, as shown in the following screenshot:

Name the new clip PlayerWalkUp.anim
and make sure you save it in the correct folder. Create this animation, as you did the downward walking one, by dragging the three appropriate images into the Dope Sheet. Change the frame rate to 6
, as done previously. You should see the following:

Dope Sheet in Animator window
Do the same thing for the right walking images. Name this animation PlayerWalkHorizontal.anim
, as shown in the following screenshot:

Planning the animation transitions
Before we begin linking up the animations, let's discuss how we plan the character to move so that the logic we use will flow naturally when we start working with the animator and start programming her movement.
The character can currently move all around the screen in an up, down, left, right, or even diagonally. The first decision that needs to be made is which animation should be used when she is walking diagonally. Do we use the side view animation or the upward and downward facing animations? I personally like the second option, as demonstrated with the following figure:

So, using the preceding image and the code we wrote in Chapter 2, Building your Project and Character look at what is happening to make her move in these ways as well as what needs to happen, as shown in the following screenshot:

Character transition
The important facts to garner from the diagram are as follows:
- Only when
movePlayerVertical
is equal to 0, will thePlayerWalkHorizontal
play - If
movePlayerHorizontal
is less than 0, thePlayerWalkHorizontal
animation must be flipped along thex-axis
- If
movePlayerVertical
is greater than 0,PlayerWalkUp
will play - If
movePlayerVertical
is less than 0,PlayerWalkDown
will play
Also, when the character stops moving, she will need to stand still, with legs together facing the same direction she was moving previously. So, now that we have a general idea of how we want her to behave based on the code, we can start working on setting up the animation.
Connecting the animation states
At the moment, our two states are not connected. So when we run the project, the hero is always standing still and facing downward; let's change that.
To tell the controller to move between the two states, we need the following prerequisites:
- A transition link between the two states
- A parameter or event to activate the transition
- Something to change the value of that parameter, usually in a script
Since we last viewed our Animator, we added two new walking animations. Return to your Animator window and adjust the position of your animations so that they look something like the following:

To allow our character to move between the animations, we need to set up Transitions between animations. She will be able to walk downward, upward, or horizontally, regardless of what her last animation was. So, this means that we want to transition from Any State to these three animations.
So, first, we create the transition between the Any State and the downward walking state by right-clicking on Any State and selecting Make Transition. This will change the mouse cursor to an arrow. Then, click on the state we want to transition to, which in this case is the PlayerWalkDown state. Do this from Any State to PlayerWalkUp and Any State to PlayerWalkHorizontal as well. When you are done, you should have something that looks like the following:

State machine for character transition
Setting up the transitions in this way tells the Animator that the character can be standing in the default state, and can go to any of the three animations and then from those animations can transition to any other animation.
Now that we have told the Animator what states can transition to these animations, we need to tell it when these transitions will occur. We will do this by setting up Parameters and Transition Conditions.
Clicking on the transition between Any State and PlayerWalkDown shows you the properties of that transition in the Inspector, as shown in the following screenshot:

PlayerWalkDown transition properties
Clicking on the arrow next to Settings will show further information, as shown in the following screenshot:

More PlayerWalkDown transition properties
As shown in the Inspector pane, by default, the new transitions are controlled by a single parameter called Exit Time, which simply means that when the first animation ends, it will transition to the second. We don't want that here as we want a specific event to control when the PlayerWalkDown animation is activated.
Change the Settings so that they appear as follows:

Changed settings for PlayerWalkDown
Change the settings for the transition between Any State and PlayerWalkUp and the transition between Any State and PlayerWalkHorizontal in the same way.
When you deselect Exit Time, you will see the following warning stating that a transition needs at least one condition:

Deselect Exit Time warning
We will give it a condition by creating a transition parameter. To add a new parameter, select the Parameters tab, click on the + symbol in the parameter section, and then select Int, as shown in the following screenshot:

Name this parameter yMove
, as shown in the following screenshot:

We will use this yMove
parameter to tell the animator when to transition to the PlayerWalkDown and PlayerWalkUp animations, as shown in the following figure:

Select the transition between Any State and PlayerWalkDown. Select the + symbol in the Conditions section. Since yMove
is our only parameter, it will automatically be placed as the condition parameter. Select Less from the drop-down menu, as shown in the following screenshot:

Selecting Less in Condition parameter
It is now stating that whenever the yMove
parameter is less than 0, the Player will run her PlayerWalkDown animation.
We will do the same thing for the transition between Any State and PlayerWalkUp, but we will leave Greater in the drop-down menu, as shown in the following screenshot:

Selecting Greater in Condition parameter
Now we can set up a parameter for the transition between Any State and PlayerWalkHorizontal. For this, we will create a Boolean parameter by selecting Bool from the new parameter menu and naming it xMove
, as shown in the following screenshot:

We will use this xMove
parameter to tell the animator when to transition to the PlayerWalkHorizontal animation, as shown in the following figure:

Now select the transition between Any State and PlayerWalkHorizontal. Change the Condition to xMove
to true,
as shown in the following screenshot:

Selecting true in condition parameter
If you run the game at this point, the character still doesn't walk when she moves. We've told the Animator when the transitions need to occur, but we haven't actually done anything to make these parameter values change. For this, we need to update our CharacterMovement
script.
Accessing controllers from a script
Now that we have an animator attached to our Player GameObject, we can adjust its parameters using scripts. To do so, we are going to update our CharacterMovement.cs
script with the following two things:
- Create a variable for the Animator so that we can reference it in the script.
- Use
GetComponent
to find the Animator component attached to the Player.
Let's first create a variable for the Animator. Add the following code to your variable declarations:
// Animator component for the player private Animator playerAnim;
Now let's reference the animator component and assign it to the new variable playerAnim
. Add the following code to your Awake()
function:
playerAnim=(Animator)GetComponent(typeof(Animator));
Now we can reference the player's animator within our script.
We also need to be able to access the player's sprite renderer from within the script. The SpriteRender
now has the ability to easily flip a sprite in the x or y direction, and we will use this property to make the character face left when walking left. We will access the sprite rendered in the same way we accessed the animator, that is, by declaring a variable and then referencing it.
Let's first create a variable for the sprite renderer. Add the following code to your variable declarations:
//Sprite renderer for the player private SpriteRenderer playerSpriteImage;
Now let's reference the sprite renderer component and assign it to the new playerSpriteImage
variable. Add the following code to your Awake()
function:
playerSpriteImage =(SpriteRenderer)GetComponent(typeof(SpriteRenderer));
Now we can reference the player's animator within our script.
Recall the values the parameters need to hold for the transitions to occur, as shown in the following screenshot:

Parameter values for state transition
And recall the conditions that will make the parameters change, as shown in the following figure:

To reflect these conditions in the code, add the following lines of code to your Update()
function:
if(movePlayerVertical!=0){ playerAnim.SetBool("xMove",false); playerSpriteImage.flipX=false; if(movePlayerVertical>0){ playerAnim.SetInteger("yMove",1); }else if(movePlayerVertical<0){ playerAnim.SetInteger("yMove",-1); } }else { playerAnim.SetInteger("yMove",0); if(movePlayerHorizontal>0){ playerAnim.SetBool("xMove",true); playerSpriteImage.flipX=false; }else if(movePlayerHorizontal<0){ playerAnim.SetBool("xMove",true); playerSpriteImage.flipX=true; }else{ playerAnim.SetBool("xMove",false); } }
Your character should now walk around the screen in all the appropriate directions. However, she won't stop walking when she stops moving! We're going to have to create a few more animations and another transition parameter to make this work appropriately.
Making her stop animating and face the correct direction
We are almost done with our character's animation. We only need to do a little more so that she will stop animating when she stops moving. To accomplish this, we will first make three idle animations, one for each of her directions. The easiest way to do this is to duplicate her walking animations and then edit them appropriately.
Select the PlayerWalkDown.anim
animation from the Project view and type Ctrl + D to duplicate the animation. Rename the new animation as PlayerIdleDown.anim
, as shown in the following screenshot:

Drag and drop the new PlayerIdleDown animation to the Player's Animator, as shown in the following screenshot:

PlayerIdleDown animation
Open the Animation window and select the new PlayerIdleDown animation from the drop-down menu. The animation will only show up in this drop-down menu if you have already added it to the animator, as shown in the following screenshot:

Delete the first, third, and fourth images and then drag the remaining image so that it is in the 0:0
position. You should now have an animation with only a single image, the image in which the character is standing still and facing downward, as shown in the following screenshot:

Repeat this process to create PlayerIdleUp
and PlayerIdleHorizontal
animations. The following screenshot shows PlayerIdleUp
:

The following screenshot shows PlayerIdleHorizontal
:

Now we need to set up our transitions in the Animator. Set up transitions from your walking animations to idle animations, as shown in the following screenshot:

Change the settings on each of these transitions to the following:

Now we will use a Boolean parameter to transition to these idle animations. Create a Bool parameter called moving
, as shown in the following screenshot:

Now, set the conditions of each of the new transitions so that they run when moving
is false, as shown in the following screenshot:

The only thing we have to do now is adjust the code to tell moving
to change from true
to false
. This is actually simpler than the preceding animation code and can be accomplished by adding the following code to the Update()
function:
if(movePlayerVertical==0 && movePlayerHorizontal==0){ playerAnim.SetBool("moving",false); }else{ playerAnim.SetBool("moving",true); }
Add the preceding code to the Update()
function before the if
statement that triggered the animations and after the statement that assigns the player's velocity.
Now your character should be able to walk around and stand around while facing the correct direction!
- C程序設計簡明教程(第二版)
- 數字媒體應用教程
- JMeter 性能測試實戰(第2版)
- 3D少兒游戲編程(原書第2版)
- Java 11 Cookbook
- SQL Server 2016數據庫應用與開發習題解答與上機指導
- RSpec Essentials
- Node Cookbook(Second Edition)
- 代替VBA!用Python輕松實現Excel編程
- Solutions Architect's Handbook
- 網絡數據采集技術:Java網絡爬蟲實戰
- Python預測之美:數據分析與算法實戰(雙色)
- Java高手是怎樣煉成的:原理、方法與實踐
- After Effects CC案例設計與經典插件(視頻教學版)
- 3D Printing Designs:The Sun Puzzle