Unity Character Animation With Mecanim - Sample Chapter
Unity Character Animation With Mecanim - Sample Chapter
Unity Character Animation With Mecanim - Sample Chapter
"Community
Experience
Distilled"
Jamie Dean
C o m m u n i t y
D i s t i l l e d
E x p e r i e n c e
Jamie Dean
Preface
Preface
In the past few years, Unity has proved itself to be a versatile, user-friendly platform
for game production and other interactive applications. With it, developers can
rapidly assemble game menus and interfaces, build levels, animate characters, and
define how these elements interact with each other.
Compared to other development tools, Unity is artist-friendly, centering on a
Scene viewport window and controls that will be familiar to anyone who has
worked with 3D software. Like all game engines, it requires scripting to enable any
complex functionality, but coding can quickly be tested and adjusted making for
a less-frustrating experience for anyone from a non-programming background.
Unity's easy-to-learn drag and drop functionality has endeared it to enthusiasts and
professionals alike. Its multiplatform publishing capabilities streamlined the creation
of all sorts of games played on PC, Mac, iOS, Android and consoles.
The personal edition of Unity can be downloaded for free, making it suitable
for entry-level game developers. The online manual and scripting reference, in
addition to the thriving developer community, make it easy to find support and
get queries answered.
The addition of Mecanim to Unity gives the independent game developer an
even more expansive toolset, making it possible to handle a significant part of
the character animation process without the use of additional software. It makes
retargeting, retiming, and adjusting existing animations a simple task without the
usual problems that accompany importing and exporting data between applications.
The modeling toolset within Unity is extremely limitedprimitive objects such as
spheres, cubes, and planes can be assembledbut if it is the actual modeling and
texturing of characters and levels that you are most interested in, you will need a
general 3D package such as 3ds Max, Maya, or blender. These aspects of building
a game are well addressed in other publications.
Preface
The context
In order to closely correspond to the development of a real game, the projects in
this book follow a theme of a typical first-person action gamethe sort that is often
found to be played on PC, console, and mobile platformsthe context is the zombie
apocalypse. During the game, our player must negotiate his or her way out of an
office complex full of zombies. In terms of character animation, this will offer us
plenty of variety in the type of movement required by the player and enemies.
Preface
Importing a rigged character model in the FBX format and adjusting import
settings
Typically, an enemy character such as this will have a series of different animation
sequences, which will be imported separately or together from a 3D package. In this
case, our animation sequences are included in separate files.
We will begin, by creating the Unity project.
[1]
3. In the Unity - Project Wizard dialog that appears, check the relevant boxes for
the Character Controller.unityPackage and Scripts.unityPackage packages.
4. Click on the Create button. It may take a few minutes for Unity to initialize.
5. Download the project ZIP file for this book from the Packt website. The file
contains a Unity assets package with the content necessary for the projects in
this book.
Downloading the example code
You can download the example code files from your account at
http://www.packtpub.com for all the Packt Publishing books you
have purchased. If you purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the
files e-mailed directly to you.
[2]
Chapter 1
The zombie model and two folders should now be visible in the FBX_Imports folder
in the Assets panel.
In the next step, we will move the imported material and texture assets into the
appropriate folders in the Unity project.
[3]
It may not be immediately visible within the Scene view due to the default import
scale settings.
We will take care of this in the next step.
[4]
Chapter 1
[5]
This character model is a medium resolution model4410 triangles and has a single
1024 x 1024 albedo texture and separate 1024 x 1024 specular and normal maps.
The character has been rigged with a basic skeleton. Creating a skeletal rig will be
discussed in detail in the next chapter. The rigging process is essential if the model is
to be animated.
We need to save our progress, before we get any further:
1. Save the scene by navigating to File | Save Scene as....
2. Choose an appropriate filename for the scene, such as Chapter1_1.
3. Click on the Apply button.
[6]
Chapter 1
Despite the fact that we have only added a single game object to the default scene,
there are more steps that we will need to take to set up the character and it will be
convenient for us to save the current set up in case anything goes wrong.
In the character animation, there are looping and single-shot animation sequences.
Some animation sequences such as walk, run, idle are usually seamless loops
designed to play back-to-back without the player being aware of where they
start and end.
Other sequences, typically, shooting, hitting, being injured or dying are often
single-shot animations, which do not need to loop. We will start with this kind,
and discuss looping animation sequences later in the book.
In order to use Mecanim's animation tools, we need to set up the character's Avatar
so that the character's hierarchy of bones is recognized and can be used correctly
within Unity.
Generic is one of the new animation formats that are compatible with Mecanim's
animator controllers. It does not have the full functionality of Mecanim's character
animation tools. Animations sequences imported with the generic format cannot
be retargeted and are best used for quadrupeds, mechanical devices, pretty much
anything except a character with two arms and two legs.
The Humanoid animation type allows the full use of Mecanim's powerful toolset.
It requires a minimum of 15 bones, and assumes that your rig is roughly human
shaped with a pair of arms and legs. It can accommodate many more intermediary
joints and some basic facial animation.
One of the greatest benefits of using the Humanoid type is that it allows animation
sequences to be retargeted or adapted to work with different rigs. For instance,
you may have a detailed player character model with a full skeletal rig (including
fingers and toes joints), maybe you want to reuse this character's idle sequence with
a background character that is much less detailed, and has a simpler arrangement
of bones.
Mecanim makes it possible reuse purpose built motion sequences and even create
useable sequences from motion capture data.
Now that we have introduced these three rig types, we need to choose the appropriate
setting for our imported zombie character, which in this case is Humanoid:
1. In the Inspector panel, click on the Rig tab.
2. Set the Animation Type field to Humanoid to suit our character skeleton type.
3. Leave Avatar Definition set to Create From This Model.
4. Optimize Game Objects can be left checked.
5. Click on the Apply button to save the settings and transfer all of the changes
that you have made to the instance in the scene.
This is how the screenshot will look like:
[8]
Chapter 1
The Humanoid animation type is the only one that supports retargeting.
So if you are importing animations that are not unique and will be used
for multiple characters, it is a good idea to use this setting.
In the next step, we will define the hierarchy of the joints in the Avatar.
[9]
The rest of the bones in the list for body, left hand, and right hand will need to be
allocated. You can scroll down in the panel to see the names of the bones from your
hierarchy and which position they have been placed in within the Avatar.
Note that the Avatar mapping definition only has two positions
available for spine bones, if the character you are mapping has more
than two bones in its spine (like this example), you can decide which
of them to use.
I usually leave out the upper-spine bone, as it typically contains very
little data in animation sequences, and because of its proximity to
the neck and shoulders, which usually have more influence on the
vertices of the model.
[ 10 ]
Chapter 1
A common occurrence at this point of the process is a red warning display in your
Scene view notifying you that the character is not in T-pose:
[ 11 ]
Chapter 1
3. Optional bones, such as the neck and toes, are quite often left out by the
automatic mapping, so it is a good idea to add them (in the appropriate
definition slots), at this stage, before you apply the settings.
If you make a mistake, just drag the correct bone onto the field
in the list to replace it.
4. When you are finished, click on Done. This will save the settings of the
Avatar and apply them to the instance of the model in the scene.
The Avatar asset will now be referenced in the Animator component of the character
game object, which can be viewed in the Inspector panel:
At this point, our Avatar is configured, creating a link to our character's skeleton
hierarchy that Unity can use.
Next, we will lay the ground work to add a simple animation that will run in
the game.
We can continue with the scene, or if you have closed Unity since working on the last
section, re-open the scene that you saved. You can open the scene by navigating to
File | Open Scene | PACKT_Scenes | Chapter1_1.
Assets imported with animation will have space for an animator controller to be
added to them. Follow these steps to create the controller:
1. Click on the PACKT_Controllers folder in the Project panel.
2. Navigate to Create | Animator Controller.
3. The Animator Controller icon will appear in the Assets panel in the lowercenter of the interface.
4. Rename this zombieControl.
5. Click on the Animator tab to open the Animator panel. If this is not visible,
add it in the menu bar by navigating to Window | Animator.
6. Drag the Animator tab above its current position to undock it as a window.
Undocking the Animator panel is not strictly necessary, especially if you
are working with on a large monitor, but it will give you more space to
view the whole state machine as it is created.
In the newly created animator controller, there are two visible states, labeled Entry
and Any State:
[ 14 ]
Chapter 1
The Entry state will usually be the starting point when the game starts or when
the character is instantiated. We can use Any State to override states, which are
currently running if we want something else to take priority.
Setting up a number of states for animation clips will enable greater control over the
implementation of the animated sequences. We will add more states in the next step.
Creating states
States are the building blocks of the animator controller. Each state includes one or
more motion clip. States are linked using Transitions, visually presenting the order
in which states will become active:
1. Create a new state by right-clicking on the empty part of the animator graph.
2. Navigate to Create State | Empty.
3. Select the state by clicking on it. Rename it Idle in the Inspector panel.
4. Create a second state in the same way. Name this Hit in the Inspector panel.
Next, we will add the appropriate animation clips to the states:
1. Click on the PACKT_Animations folder within the Project panel.
2. In the Assets panel, expand both the zombie_idle and zombie_attack
animation assets by clicking on the small arrow on the right side of their
icons.
3. Select the Idle state in the Animator window.
4. Drag the zombie_idle animation to the Motion slot in the Inspector panel:
[ 15 ]
5. Select the Hit state and drag the hit animation from the expanded
zombie_attack asset into the Motion slot in the Inspector panel:
These animations are now tied to the states that we have set up.
At the moment, the states are unconnected. To connect them, you need to create
a parameter that will define the conditions that cause the character to switch to
another state.
Creating a parameter
In the Animator interface, parameters are used to specify when states will run. They
are similar to variables in Unity scripts and can take the form of integers, floats, and
booleans. To create a parameter follow these steps:
1. In the upper-left of the Animator window, click on the Parameters tab and
the + symbol to create a new parameter.
2. Choose Trigger from the list.
In Mecanim, a trigger parameter allows you to allow a quick action. It is ideal
for attack states because it is reset each time it is fired off.
3. Name the parameter Hits
This trigger parameter will determine when the zombie's attack animation will play.
[ 16 ]
Chapter 1
Adding transitions
The next stage is to create transitions between your two states. Transitions show how
states are connected in the Animator window:
1. Right click on the Idle state in the Animator window.
2. Select Make Transition.
3. Click once on the Hit state.
The transition is displayed as a white line with an arrow indicating its direction:
We also need to create a transition from Hit back to Idle, so the character will stop
playing this animation:
1. Right click on Hit and click once on Idle to create the return transition.
In the animator controller, it is the transitions that contain the parameters.
2. Click once on the transition pointing from Idle to Hit. Its setting will appear
in the Inspector panel.
The only change that needs to be made to the default settings, at this stage, is
to change the drop down in the Conditions box at the bottom of the panel.
3. Click on the arrow and select the Hits parameter from the list.
[ 17 ]
As we want the full attack animation to play out, we will leave the Conditions box
in the return transition with its default setting Exit Time. This will set the state to
transition out once the animation has played through:
The Animation controller is now complete. We will add it to the male zombie
character in the next step:
[ 18 ]
Chapter 1
You will find the completed code (in both languages), in the project files.
[ 19 ]
6. Within the curly brackets of the Start function, add the following line
of code:
thisAnimator = GetComponent(Animator);
Because this code is in Start, as soon as the script runs, it will gain access
to the animator component and store this in the thisAnimator variable for
future use.
Next, we will add some code to the Update function. Unlike Start, which
runs only once, when the script is first activated, Update runs every frame,
so it is usually the best place to check for input.
7. Add the following code within the curly brackets of the Update function:
if(Input.GetButton("Fire1"))
{
thisAnimator.SetTrigger("Hits");
}
In the first line of code, we check for input from the Fire1 button (set up by
default for the left-mouse button). When this condition is met, we trigger the
Hits parameter inside the animator controller, enabling the transition to the
Hit state and playing the zombie_hit animation.
8. Save the script in MonoDevelop by navigating to File | Save.
If any errors appear in the console, be careful that you have not left out any
semicolons (that should end all operations and variables) or curly brackets
(that should start and end all functions and statements).
If you are including any comments for your own references, make
sure that single-line comments are preceded with two forward
slashes // and block comments are encapsulated by /* and */.
This is a pretty short, simple script. We will be elaborating on this later in the book.
We need to add the script to the zombie character. This can be done by dragging the
script from the Project panel onto the zombie_m game object in the Hierarchy panel
to attach it as a component.
Next, we will make a few small adjustments to the scene, to make it easier to view
our animation.
[ 20 ]
Chapter 1
[ 21 ]
This will cause the hit animation to play once before transitioning back to the
Idle state.
Summary
In this chapter, we covered the major steps involved in animating a premade
character using the Mecanim system in Unity.
We started with FBX import settings for the model and the rig.
Then we covered the creation of the Avatar by defining the bones in the Avatar
Definition settings.
After that we created a simple example of an animator controller, added it to the
character, and added some prepared motion clips.
Finally, we got our male zombie character up and attacking, by writing and
implementing a simple control script.
In the next chapter, we will demonstrate the process of rigging a character in 3ds
Max and Maya for use in Unity and Mecanim. This time we will start with the male
zombie's female counterpart.
[ 22 ]
www.PacktPub.com
Stay Connected: