Tuesday, 26 August 2014

Avatar Masks

Avatar Body Mask

Specific body parts can be selectively enabled or disabled in an animation using a so-called Body Mask. Body masks are used in the Animation tab of the mesh import inspector and Animation Layers. Body masks enable you to tailor an animation to fit the specific requirements of your character more closely. For example, you may have a standard walking animation that includes both arm and leg motion, but if a character is carrying a large object with both hands then you wouldn't want his arms to swing by his sides as he walks. However, you could still use the standard walking animation by switching off the arm movements in the body mask.
The body parts included are: Head, Left Arm, Right Arm, Left Hand, Right Hand, Left Leg, Right Leg and Root (which is denoted by the “shadow” under the feet). In the body mask, you can also toggle inverse kinematics (IK) for hands and feet, which will determine whether or not IK curves will be included in animation blending.
  • Click the avatar section to toggle inclusion or exclusion (green/red)
  • Double click in empty space surrounding the avatar to toggle all
Body mask in the Body Mask inspector (arms excluded)
Body mask in the Body Mask inspector (arms excluded)
In the Animation tab of the mesh import inspector, you will see a list entitled Clips that contains all the object’s animation clips. When you select an item from this list, options for the clip will be shown, including the body mask editor.
You can also create Body Mask Assets (Assets->Create->Avatar Body Mask), which show up as .mask files on disk.
The BodyMask assets can be reused in Animator Controllers, when specifying Animation Layers
A benefit of using body masks is that they tend to reduce memory overheads since body parts that are not active do not need their associated animation curves. Also, the unused curves need not be calculated during playback which will tend to reduce the CPU overhead of the animation.

Avatar Skeleton Mask

similar to AvatarBodyMask, except used for generic animations.

Human Template files

You can save the mapping of bones in your skeleton to the Avatar on disk as a “human template file” (extention *.ht), which can be reused by any characters that use this mapping. This is useful, for example, if your animators use a consistent layout and naming convention for all skeleton but Mecanim doesn’t know how to interpret it. You can then Load the .ht file for each model, so that manual remapping only needs to be done once.

Humanoid Avatars

Creating the Avatar

After a model file (FBX, COLLADA, etc.) is imported, you can specify what kind of rig it is in the Rig tab of the ModelImporter options.

Humanoid animations

For a Humanoid rig, select Humanoid and click Apply. Mecanim will attempt to match up your existing bone structure to the Avatar bone structure. In many cases, it can do this automatically by analysing the connections between bones in the rig.
If the match has succeeded, you will see a check mark next to the Configure menu
Also, in the case of a successful match, an Avatar sub-asset is added to the model asset, which you will be able to see in the project view hierarchy.
Models with and without an Avatar sub-asset
Models with and without an Avatar sub-asset
The inspector for an Avatar asset
The inspector for an Avatar asset
If Mecanim was unable to create the Avatar, you will see a cross next to the Configure button, and no Avatar sub-asset will be added. When this happens, you need to configure the avatar manually.

Non-humanoid animations

Two options for non-humanoid animation are provided: Generic and Legacy. Generic animations are imported using the Mecanim system but don’t take advantage of the extra features available for humanoid animations. Legacy animations use the the animation system that was provided by Unity before Mecanim. There are some cases where it is still useful to work with legacy animations (most notably with legacy projects that you don’t want to update fully) but they are seldom needed for new projects. 

Configuring the Avatar

Since the Avatar is such an important aspect of the Mecanim system, it is important that it is configured properly for your model. So, whether theautomatic Avatar creation fails or succeeds, you need to go into the Configure Avatar mode to ensure your Avatar is valid and properly set up. It is important that your character’s bone structure matches Mecanim’s predefined bone structure and that the model is in T-pose.
If the automatic Avatar creation fails, you will see a cross next to the Configure button.
If it succeeds, you will see a check/tick mark:
Here, success simply means all of the required bones have been matched but for better results, you might want to match the optional bones as well and get the model into a proper T-pose.
When you go to the Configure … menu, the editor will ask you to save your scene. The reason for this is that in Configure mode, the Scene View is used to display bone, muscle and animation information for the selected model alone, without displaying the rest of the scene.
Once you have saved the scene, you will see a new Avatar Configuration inspector, with a bone mapping.
The inspector shows which of the bones are required and which are optional - the optional ones can have their movements interpolated automatically. For Mecanim to produce a valid match, your skeleton needs to have at least the required bones in place. In order to improve your chances for finding a match to the Avatar, name your bones in a way that reflects the body parts they represent (names like “LeftArm”, “RightForearm” are suitable here).
If the model does NOT yield a valid match, you can manually follow a similar process to the one used internally by Mecanim:-
  1. Sample Bind-pose (try to get the model closer to the pose with which it was modelled, a sensible initial pose)
  2. Automap (create a bone-mapping from an initial pose)
  3. Enforce T-pose (force the model closer to T-pose, which is the default pose used by Mecanim animations)
If the auto-mapping (Mapping->Automap) fails completely or partially, you can assign bones by either draging them from the Scene or from theHierarchy. If Mecanim thinks a bone fits, it will show up as green in the Avatar Inspector, otherwise it shows up in red.
Finally, if the bone assignment is correct, but the character is not in the correct pose, you will see the message “Character not in T-Pose”. You can try to fix that with Enforce T-Pose or rotate the remaining bones into T-pose.

Avatar Body Masks

Sometimes it is useful to restrict an animation to specific body parts. For example, an walking animation might involve the character swaying his arms but if he picks up a gun, he should hold it in front of him. You can use an Avatar Body Mask to specify which parts of a character an animation should be restricted to.

Muscle setup

Mecanim allows you to control the range of motion of different bones using Muscles.
Once the Avatar has been properly configured, Mecanim will “understand” the bone structure and allow you to start working in the Muscles tab of the Avatar Inspector. Here, it is very easy to tweak the character’s range of motion and ensure the character deforms in a convincing way, free from visual artifacts or self-overlaps.
You can either adjust individual bones in the body (lower part of the view) or manipulate the character using predefined deformations which operate on several bones at once (upper part of the view).

Muscle Clips

In the Animation tab, you can set up Muscle Clips, which are animations for specific muscles and muscle groups.
You can also define which body parts these muscle clips apply to.

Retargeting of Humanoid animations

One of the most powerful features of Mecanim is retargeting of humanoid animations. This means that with relative ease, you can apply the same set of animations to various character models. Retargeting is only possible for humanoid models, where an Avatar has been configured, because this gives us a correspondence between the models’ bone structure.

Recommended Hierarchy structure

When working with Mecanim animations, you can expect your scene to contain the following elements:-
  • The Imported character model, which has an Avatar on it.
  • The Animator Component, referencing an Animator Controller asset.
  • A set of animation clips, referenced from the Animator Controller.
  • Scripts for the character.
  • Character-related components, such as the Character Controller.
Your project should also contain another character model with a valid Avatar.
The recommended setup is to:
  • Create a GameObject in the Hierarchy that contains Character-related components
  • Put the model as a child of the GameObject, together with the Animator component
  • Make sure scripts referencing the Animator are looking for the animator in the children instead of the root; use GetComponentInChildren<Animator>() instead of GetComponent<Animator>().
Then in order to reuse the same animations on another model, you need to:
  • Disable the original model
  • Drop in the desired model as another child of GameObject
  • Make sure the Animator Controller property for the new model is referencing the same controller asset
  • Tweak the character controller, the transform, and other properties on the top-level GameObject, to make sure that the animations work smoothly with the new model.
  • You’re done!
Previous
Muscle setup

Blend Tress

Blend Trees

A common task in game animation is to blend between two or more similar motions. Perhaps the best known example is the blending of walking and running animations according to the character’s speed. Another example is a character leaning to the left or right as he turns during a run.
It is important to distinguish between Transitions and Blend Trees. While both are used for creating smooth animation, they are used for different kinds of situations.
  • Transitions are used for transitioning smoothly from one Animation State to another over a given amount of time. Transitions are specified as part of an Animation State Machine. A transition from one motion to a completely different motion is usually fine if the transition is quick.
  • Blend Trees are used for allowing multiple animations to be blended smoothly by incorporating parts of them all to varying degrees. The amount that each of the motions contributes to the final effect is controlled using a blending parameter, which is just one of the numeric animation parameters associated with the Animator Controller. In order for the blended motion to make sense, the motions that are blended must be of similar nature and timing. Blend Trees are a special type of state in an Animation State Machine.
Examples of similar motions could be various walk and run animations. In order for the blend to work well, the movements in the clips must take place at the same points in normalized time. For example, walking and running animations can be aligned so that the moments of contact of foot to the floor take place at the same points in normalized time (e.g. the left foot hits at 0.0 and the right foot at 0.5). Since normalized time is used, it doesn't matter if the clips are of different length.

Using Blend Trees

To start working with a new Blend Tree, you need to:
  1. Right-click on empty space on the Animator Controller Window.
  2. Select Create State > From New Blend Tree from the context menu that appears.
  3. Double-click on the Blend Tree to enter the Blend Tree Graph.
The Animator Window now shows a graph of the entire Blend Tree while the Inspector shows the currently selected node and its immediate children.
The Animator Window shows a graph of the entire Blend Tree. To the left is a Blend Tree with only the root Blend Node. To the right is a Blend Tree with a root Blend Node and three Animation Clips as child nodes.
The Animator Window shows a graph of the entire Blend Tree. To the left is a Blend Tree with only the root Blend Node. To the right is a Blend Tree with a root Blend Node and three Animation Clips as child nodes.
This gives a graphical visualization of how the animations are combined as the parameter value changes (as you drag the slider, the arrows from the tree root change their shading to show the dominant animation clip).
You can select any of the nodes in the Blend Tree graph to inspect it in the Inspector. If the selected node is an Animation Clip the Inspector for that Animation Clip will be shown. The settings will be read-only if the animation is imported from a model. If the node is a Blend Node, the Inspector for Blend Nodes will be shown.
A Blend Node shown in the inspector before any motions have been added.

A Blend Node shown in the inspector before any motions have been added.

You can choose either 1D or 2D blending from the Blend Type menu; the differences between the two types are described on their own pages in this section.

Blend Trees and Root Motion

The blending between animations is handled using linear interpolation (ie, the amount of each animation is an average of the separate animations weighted by the blending parameter). However, you should note that root motion is not interpolated in the same way. See the page about root motion for further details about how this might affect your characters.

1-D Blending

The first option in the Inspector of a Blend Node is the The Blend Type. This drop-down is used to select one of the different blend types that can blend according to one or two parameters. 1D Blending blends the child motions according to a single parameter.
After setting the Blend Type, the first thing you need is to select the Animation Parameter that will control this Blend Tree. In this example, the parameter is direction which varies between –1.0 (left) and +1.0 (right), with 0.0 denoting a straight run without leaning.
Then you can add individual animations by clicking the small “+” button and selecting Add Motion Field from the popup menu. When you’re done, it should look something like this:
A 1D Blend Node with three Animation Clips.

A 1D Blend Node with three Animation Clips.

The diagram at the top of the Inspector shows the influence of each of the child motions as the parameter varies between its minimum and maximum values. Each motion is shown as a little blue pyramid (the first and last are only shown in half), and if you click and hold down the left mouse button on one them, the corresponding motion is highlighted in the motion list below. The peak of each pyramid defines the parameter value where the motion has full influence, meaning that its animation weight is 1 and the other animations have a weight of 0. This is also called thethreshold of the motion.
The diagram at the top of the Blend Node Inspector visualizes the weights of the child motions over the range of the parameter values.
The red vertical bar indicates the value of the Parameter. If you press Play in the Preview at the bottom of the Inspector and drag the red bar in the diagram left and right, you can see how the value of the parameter is controlling the blending of the different motions.

Parameter Range

The range of the parameter used by the Blend Node is shown below the diagram as two numbers to the left and right. Either one of them can be changed by clicking on the number and dragging left or right with the mouse. Note that the values correspond to the threshold of the first and last motion in the motion list.

Thresholds

You can change the threshold value of a motion by clicking on its corresponding blue pyramid in the diagram and dragging it left or right. If the “Automate Thresholds” toggle is not enabled, you can also edit the threshold value of a motion in the motion list by typing in a number in the number field in the Threshold column.
Below the motion list is the checkbox Automate Thresholds. Enabling it will distribute the thresholds of the motions evenly across the parameter range. For example, if there are five clips and the parameter ranges from –90 to +90, the thresholds will be set to –90, –45, 0, +45 and +90 in order.
The Compute Thresholds drop-down will set the thresholds from data of your choice obtained from the root motions in the Animation Clips. The data that is available to choose from is speed, velocity x, y, or z, and angular speed in degrees or radians. If your parameter corresponds to one of these properties, you can compute the thresholds using the Compute Thresholds drop-down.
Property:Function:
SpeedSets the threshold of each motion according to its speed (the magnitude of the velocity).
Velocity XSets the threshold of each motion according to its velocity.x.
Velocity YSets the threshold of each motion according to its velocity.y.
Velocity ZSets the threshold of each motion according to its velocity.z.
Angular Speed (Rad)Sets the threshold of each motion according to its angular speed in radians per second.
Angular Speed (Deg)Sets the threshold of each motion according to its angular speed in degrees per second.
Say, for example, you had a walk animation that covered 1.5 units per second, a jog at 2.3 units per second, and a run at 4 units per second, choosing the Speed option from the drop-down would set the parameter range and thresholds for the three animations based on these values. So, if you set the speed parameter to 3.0, it would blend the jog and run with a slight bias toward the jog.

2D Blending

The first option in the Inspector of a Blend Node is the The Blend Type. This drop-down is used to select one of the different blend types that can blend according to one or two parameters. The 2D blending types blends the child motions according to two parameters.
The different 2D Blend Types have different uses that they are suitable for. They differ in how the influence of each motion is calculated.
2D Simple Directional: Best used when your motions represent different directions, such as “walk forward”, “walk backward”, “walk left”, and “walk right”, or “aim up”, “aim down”, “aim left”, and “aim right”. Optionally a single motion at position (0, 0) can be included, such as “idle” or “aim straight”. In the Simple Directional type there should not be multiple motions in the same direction, such as “walk forward” and “run forward”.
2D Freeform Directional: This blend type is also used when your motions represent different directions, however you can have multiple motions in the same direction, for example “walk forward” and “run forward”. In the Freeform Directional type the set of motions should always include a single motion at position (0, 0), such as “idle”.
2D Freeform Cartesian: Best used when your motions do not represent different directions. With Freeform Cartesian your X parameter and Y parameter can represent different concepts, such as angular speed and linear speed. An example would be motions such as “walk forward no turn”, “run forward no turn”, “walk forward turn right”, “run forward turn right” etc.
After setting the Blend Type, the first thing you need is to select the two Animation Parameters that will control this Blend Tree. In this example, the parameters are velocityX (strafing) and velocityZ (forward speed).
Then you can add individual animations by clicking + -> Add Motion Field to add an Animation Clip to the blend tree. When you’re done, it should look something like this:
A 2D Blend Node with five Animation Clips.

A 2D Blend Node with five Animation Clips.

The positions in 2D blending are like the thresholds in 1D blending, except that there are two values instead of one, corresponding to each of the two parameters. Their positions along the horizontal X axis correspond to the first parameter, and their positions along the vertical Y axis correspond to the second parameter. A walking forward animation might have a velocityX of 0 and a velocityZ of 1.5, so those values should be typed into the Pos X and Pos Y number fields for the motion.

The 2D Blending Diagram

The diagram at the top of the Inspector shows the positions of the child motions in the 2D blend space. The motions are shown as blue dots. Motions with no Animation Clip or Blend Tree assigned have no influence on the blend and are shown as gray dots. You can select a motion by clicking on its dot in the diagram. Once selected, the influence of that motion for each point in the blending space is visualized as a blue field. The field is strongest right under the position of the motion, where the motion has full influence, meaning that its animation weight is 1 and the other animations have a weight of 0. Further away the influence decreases as the influence of other motions take over.
The diagram at the top of the Blend Node Inspector visualizes the weights of the child motions over the extends of the parameter values.
The red dot indicates the values of the two Parameters. If you press Play in the Preview at the bottom of the Inspector and drag the red dot in the diagram around, you can see how the values of the parameters are controlling the blending of the different motions. In the diagram you can also see the influence of each motion represented as circles around each motion. You will see that if you move the red dot on top of one of the blue dots representing a motion, the circle for that motion gains its maximum radius and the circles for all other motions shrink down to nothing. At positions that are in between several motions, multiple of the nearby motions will have an influence on the blend. If you select one of the motions in order to see the blue influence field of that motion, you can see that as you move the red dot around, the circle size of the motion corresponds exactly with how strong the influence field is at various positions.
When no motion is selected, the diagram shows a mix of all the influence fields that is more blue where a single motion dominates and less blue where many motions contribute to the blend.

Positions

You can change the positions of a motion by clicking on its corresponding blue dot in the diagram and dragging it around. You can also edit position coordinates of a motion in the motion list by typing in numbers in the number fields in the Pos X and Pos Y columns.
The Compute Positions drop-down will set the positions from data of your choice obtained from the root motions in the Animation Clips. The data that is available to choose from is speed, velocity x, y, or z, and angular speed in degrees or radians. If one or both of your parameters correspond to one of these properties, you can compute the Pos X and/or Pos Y using the Compute Positions drop-down.
Property:Function:
Velocity XZSets the Pos X of each motion according to its velocity.x and the Pos Y according to its velocity.z.
Speed And Angular SpeedSets the Pos X of each motion according to its angular speed (in radians per second) and the Pos Y according to its speed.
Furthermore you can mix and match by choosing Compute Position -> X Position From and/or Compute Position -> Y Position From to only auto-compute one of them at a time, leaving the other unchanged.
Property:Function:
SpeedSets the Pos X or Pos Y of each motion according to its speed (the magnitude of the velocity).
Velocity XSets the Pos X or Pos Y of each motion according to its velocity.x.
Velocity YSets the Pos X or Pos Y of each motion according to its velocity.y.
Velocity ZSets the Pos X or Pos Y of each motion according to its velocity.z.
Angular Speed (Rad)Sets the Pos X or Pos Y of each motion according to its angular speed in radians per second.
Angular Speed (Deg)Sets the Pos X or Pos Y of each motion according to its angular speed in degrees per second.
Say, for example, that your parameters correspond to sideways velocity and forward velocity, and that you have an idle animation with an average velocity (0, 0, 0), a walk animation with (0, 0, 1.5), and two strafe animations with velocities of (–1.5, 0, 0) and (1.5, 0, 0) respectively. Choosing theVelocity XZ option from the drop-down would set the positions of the motions according to the X and Z coordinates of those velocities.

Additional Blend Tree Options

The options below are common to both 1D and 2D blending.

Time Scale

You can alter the “natural” speed of the animation clips using the animation speed number fields (the columns with a clock icon at the top), so you could make the walk twice as fast by using a value of 2.0 as its speed. The Adjust Time Scale > Homogeneous Speed button rescales the speeds of the clips so that they correspond with the chosen minimum and maximum values of the parameter but keep the same relative speeds they initially had.
Note that the Adjust Time Scale drop-down is only available if all the motions are Animation Clips and not child Blend Trees.

Mirroring

You can mirror any humanoid Animation Clip in the motions list by enabling the mirror toggle at the far right. This feature enables you to use the same animation in its original form and in a mirrored version without needing twice the memory and space.

Animator Controller

Animator Controller
The Animator Controller is the main component by which animation behaviour is added to an object.

Creating an Animator Controller

You can view and set up character behaviour from the Animator Controller view (Menu: Window > Animator Controller).
The various ways an Animator Controller can be created:
·         From the Project View by selecting ‘Create > Animator Controller’.
·         By right-clicking in the Project View and selecting ‘Create > Animator Controller’.
·         From the Assets menu by selecting ‘Assets > Create > Animator Controller’.
This creates a .controller asset on disk, which looks like this in the Project Browser
Animator Controller asset on disk
Animator Controller asset on disk
After the state machine setup has been made, you can drop the controller onto the Animator component of any character with an Avatar in the Hierarchy View.
The Animator Controller Window
The Animator Controller Window
The Animator Controller window will contain
·         The Animation Layer Widget (top-left corner)
·         The Event Parameters Widget (bottom-left)
·         The visualization of the State Machine itself.
Note that the Animator Controller Window will always display the state machine from the most recently selected .controller asset, regardless of what scene is currently loaded.

Animation States

Animation States are the basic building blocks of an Animation State Machine. Each state contains an individual animation sequence (or blend tree) which will play while the character is in that state. When an event in the game triggers a state transition, the character will be left in a new state whose animation sequence will then take over.
When you select a state in the Animator Controller, you will see the properties for that state in the inspector:-

Property:
Function:
Speed
The default speed of the animation
Motion
The animation clip assigned to this state
Foot IK
Should Foot IK be respected for this state
Transitions
The list of transitions originating from this state

The default state, displayed in brown, is the state that the machine will be in when it is first activated. You can change the default state, if necessary, by right-clicking on another state and selecting Set As Default from the context menu. The solo and mute checkboxes on each transition are used to control the behaviour of animation previews - see this page for further details.
A new state can be added by right-clicking on an empty space in the Animator Controller Window and selecting Create State->Empty from the context menu. Alternatively, you can drag an animation into the Animator Controller Window to create a state containing that animation. (Note that you can only drag Mecanim animations into the Controller - non-Mecanim animations will be rejected.) States can also contain Blend Trees.

Any State

Any State is a special state which is always present. It exists for the situation where you want to go to a specific state regardless of which state you are currently in. This is a shorthand way of adding the same outward transition to all states in your machine. Note that the special meaning of Any State implies that it cannot be the end point of a transition (ie, jumping to “any state” cannot be used as a way to pick a random state to enter next).
Animation Transitions
Animation Transitions define what happens when you switch from one Animation State to another. There can be only one transition active at any given time.
Property:
Function:
Atomic
Is this transition atomic? (cannot be interrupted)
Conditions
Here we decide when transitions get triggered.
A condition consists of:
·         An event parameter or an Exit Time, specifying a number which represents the normalized time of the source state (e.g. 0.95 means the transition will trigger, when we’ve played the source clip 95% through).
·         A conditional predicate, if needed (for example Less/Greater for floats).
·         A parameter value (if needed).
You can adjust the transition between the two animation clips by dragging the start and end values of the overlap.