Animation features in Unity 5

15 min read

In this article by Valera Cogut, author of the book Unity 5 for Android Essentials you will learn new Mecanim animation features and awesome new audio features in Unity 5.

(For more resources related to this topic, see here.)

New Mecanim animation features in Unity 5

Unity 5 contains some new awesome possibilities for the Mecanim animation system. Let’s look at the new shiny features known in Unity 5.

State machine behavior

Now, you can inherit your classes from StateMachineBehaviour in order to be able to attach them to your Mecanim animation states. This class has the following very important callbacks:

  • OnStateEnter
  • OnStateUpdate
  • OnStateExit
  • OnStateMove
  • OnStateIK

The StateMachineBehaviour scripts behave like MonoBehaviour scripts, which you can attach on as many objects as you wish; the same is true for StateMachineBehaviour. You can use this solution with or without any animation at all.

State machine transition

Unity 5 introduced a new awesome feature for Mecanim animation systems known as state machine transitions in order to construct a higher abstraction level. In addition, entry and exit nodes were created. By these two additional nodes to StateMachine, you can now branch your start or finish state depending on your special conditions and requirements.

These mixes of transitions are possible: StateMachine | StateMachine, State | StateMachine, State | State.

In addition, you also can reorder your layers or parameters. This is the new UI that allows it by a very simple and useful drag-n-drop method.

Asset creation API

One more awesome possibility in Unity 5 was introduced using scripts in Unity Editor in order to programmatically create assets, such as layers, controllers, states, StateMachine, and blend trees. You can use different solutions with a high-level API provided by Unity engine maintenance and a low-level API, where you should manage all your assets manually. You can find more about both API versions on Unity documentation pages.

Direct blend tree

Another new feature that was introduced with the new BlendTree type is known as direct. It provides direct mapping and animator parameters to the weight of BlendTree children.

Possibilities with Unity 5 have been enhanced with two useful features for Mecanim animation system:

  • Camera can scale, orbit, and pan
  • You can access your parameters in runtime

Programmatically creating assets by Unity 5 API

The following code snippets are self-explanatory, pretty simple, and straightforward. I list them just as a very useful reminder.

Creating the controller

To create a controller you can use the following code:

var animatorController = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath ("Assets/Your/Folder/Name/state_machine_transitions.controller");

Adding parameters

To add parameters to the controller, you can use this code:

animatorController.AddParameter("Parameter1", UnityEditor.Animations.AnimatorControllerParameterType.Trigger);
animatorController.AddParameter("Parameter2", UnityEditor.Animations.AnimatorControllerParameterType.Trigger);
animatorController.AddParameter("Parameter3″, UnityEditor.Animations.AnimatorControllerParameterType.Trigger);

Adding state machines

To add state machines, you can use the following code:

var sm1 = animatorController.layers[0].stateMachine;
var sm2 = sm1.AddStateMachine("sm2");
var sm3 = sm1.AddStateMachine("sm3");

Adding states

To add states, you can use the code given here:

var s1 = sm2.AddState("s1″);
var s2 = sm3.AddState("s2″);
var s3 = sm3.AddState("s3″);

Adding transitions

To add transitions, you can use the following code:

var exitTransition = s1.AddExitTransition();
exitTransition.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "Parameter1");
exitTransition.duration = 0;
 
var transition1 = sm2.AddAnyStateTransition(s1);
transition.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "Parameter2");
transition.duration = 0;
 
var transition2 = sm3.AddEntryTransition(s2);
transition2.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "Parameter3″);
sm3.AddEntryTransition(s3);
sm3.defaultState = s2;
 
var exitTransition = s3.AddExitTransition();
exitTransition.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "Parameter3");
exitTransition.duration = 0;
 
var smt = rootStateMachine.AddStateMachineTransition(sm2, sm3);
smt.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "Parameter2");
sm2.AddStateMachineTransition(sm1, sm3);

Going deeper into new audio features

Let’s start with new amazing Audio Mixer possibilities.

Now, you can do true submixing of audio in Unity 5.

In the following figure, you can see a very simple example with different sound categories required in a game:

Now in Unity 5, you can mix different sound collections within categories and tune up volume control and effects only once in a single place so that you can save a lot of time and effort. This new awesome audio feature in Unity 5 allows you to create a fantastic mood and atmosphere for your game.

Each Audio Mixer can have a hierarchy of AudioGroups:

The Audio Mixer can not only do a lot of useful things, but also mix different sound groups in one place. Different audio effects are applied sequentially in each AudioGroup.

Now you’re getting closer to the amazing, awesome, and shiny new features in Unity 5 for audio system! A callback script OnAudioFilterRead, which made possible the processing of samples directly into their scripts, previously was handled exclusively by the code.

Unity now also supports custom plugins to create different effects. With these innovations, Unity 5 for audio system now has its own applications synthesizer, which has become much easier and more flexible than possible.

Mood transitions

As mentioned earlier, the mood of the game can be controlled with a mix of sound. This can be achieved with the involvement of new stems and music or ambient sounds. Another common way to accomplish this is to move the state of the mixture. A very effective way of taking mood where you want to go is by changing the volume section’s mixture and transferring it to the different states of effect parameters.

Inside, everything is the Audio Mixer’s ability to identify pictures. Pictures capture the status of all parameters in Audio Mixer. Everything from investigative wet levels to AudioGroup tone levels can be captured and moved between the various parameters.

You can even create a complex mixture of states between a whole bunch of pictures in your game, creating all kinds of possibilities and goals.

Imagine installing all these things without having to write a line of code to the script.

Physics and particle system effects in Unity 5

Physics for 2D and 3D in Unity are very similar, because they use the same concepts like Ias rigidbodies, joints, and colliders. However, Box2D has more features than Unity’s 2D physics engine. It is not a problem to mix 2D and 3D physics engines (built-in, custom, third-party) in Unity. So, Unity provides an easy development way for your innovative games and applications.

If you need to develop some real-life physics in your project, then you should not write your own library, framework, or engine, except specific requirements. However, you should try existing physics engines, libraries, or frameworks with many features already made.

Let’s start our introduction into Unity’s built-in physics engine. In the case that you need to set your object under Unity’s built-in physics management, you just need to attach the Rigidbody component to this object. After that, your object can collide with other entities in its world and gravity will have an affect on it. In other words, Rigidbody will be simulated physically. In your scripts, you can move any of your Rigidbodies by adding vector forces to them.

It is not recommended to move the Transform component of a non-kinematic Rigidbody, because it will not collide correctly with other items. Instead, you can apply forces and torque to your Rigidbody.

A Rigidbody can be used also to develop cars with wheel colliders and with some of your scripts to apply forces to it. Furthermore, a Rigidbody is used not only for vehicles, but also you can use it for any other physics issues such as airplanes, robots with various scripts for applying forces, and with joints.

The most useful way to utilize a Rigidbody is to use it in collaboration with some primitive colliders (built-in in Unity) such as BoxCollider and SphereCollider. Next, we will show you two things to remember about Rigidbody:

  • In your object’s hierarchy, you must never have a child and its parent with the Rigidbody component together at the same time
  • It is not recommended to scale Rigidbody’s parent object

One of the most important and fundamental components of physics in Unity is a Rigidbody component. This component activates physics calculations on the attached object. If you need your object to react to collisions( for example, while playing billiards, balls collide with each other and scatter in different directions) then you must also attach a Collider component on your GameObject. If you have attached a Rigidbody component to your object, then your object will move through the physics engine, and I recommend that you do not move your object by changing its position or rotation in the Transform component. If you need some way to move your object, you should apply the various forces acting on the object so that the Unity physics engine assumes all obligations for the calculation of collisions and moving dynamic objects. Also, in some situations, there is a need for a Rigidbody component, but your object must be moved only by changing its position or rotation properties in the Transform component. It is sometimes necessary to use components without Rigidbody calculating collisions of the object and its motion physics. That is, your object will move by your script or, for example, by running your animation. In order to solve this problem, you should just activate its IsKinematic property. Sometimes, it is required to use a combination of these two modes when IsKinematic is turned on and when it is turned off. You can create a symbiosis of these two modes, changing the IsKinematic parameter directly in your code or in your animation.

Changing the IsKinematic property very often from your code or from your animation can be the cause of overhead in your performance. Therefore, you should use it very carefully and only when you really need it.

A kinematic Rigidbody object is defined by the IsKinematic toggle option. If a Rigidbody is Kinematic, this object will not be affected by collisions, gravity, or forces.

There is a Rigidbody component for 3D physics engine and an analogous Rigidbody2D for 2D physics engine.

A kinematic Rigidbody can interact with other non-kinematic Rigidbodies. In the event of using kinematic Rigidbodies, you should translate their positions and rotation values of the Transform component by your scripts or animations. When there is a collision between Kinematic and non-kinematic Rigidbodies, then the Kinematic object will properly wake up non-kinematic Rigidbody. Furthermore, the first Rigidbody will apply friction to the second Rigidbody if the second object is on top of the first object.

Let’s list some possible usage examples of kinematic Rigidbodies:

  • There are situations when you need your objects to be under physics management, but sometimes to be controlled explicitly from your scripts or animations. As an example, you can attach Rigidbodies to the bones of your animated personage and connect them with joints in order to utilize your entity as a ragdoll. If you are controlling your character by Unity’s animation system, you should enable the IsKinematic checkbox. Sometimes you may require your hero to be affected by Unity’s built-in physics engine if you are hitting the hero. In this case you should disable the IsKinematic checkbox.
  • If you need a moving item that can push different items, yet not by itself. In case you have a moving platform and you need to place some Rigidbody objects on top, you ought to enable the IsKinematic checkbox rather than simply attaching a collider without a Rigidbody.
  • You may need to enable the IsKinematic property of your Rigidbody object that is animated and has a genuine Rigidbody follower by utilizing one of the accessible joints.

Earlier, I mentioned the collider, but now is the time to discuss this component in more detail. In the case of Unity, the physics engine can calculate collisions. You must specify geometric shapes for your object by attaching the Collider component. In most cases, the collider does not have to be the same shape as your mesh with many polygons. Therefore, it is desirable to use simple colliders, which will significantly improve your performance, otherwise with more complex geometric shapes you risk significantly increasing the computing time for physics collisions. Simple colliders in Unity are known as primitive colliders: BoxCollider, BoxCollider2D, SphereCollider, CircleCollider2D, and CapsuleCollider. Also, no one forbids you to combine different primitive colliders to create a more realistic geometric shape that the physics engine can handle very fast compared to MeshCollider. Therefore, to accelerate your performance, you should use primitive colliders wherever possible. You can also hang on to the child objects of different primitive colliders, which will change its position and rotation, depending on the parent Transform component. The Rigidbody component must be attached only to the GameObject root in the hierarchy of your entity.

Unity provides a MeshCollider component for 3D physics and a PolygonCollider2D component for 2D physics. The MeshCollider component will use your object’s mesh for its geometric shape. In PolygonCollider2D, you can edit directly in Unity and create any 2D geometry for your 2D physical computations. In order to react in collisions between different mesh colliders, you must enable a Convex property. You will certainly sacrifice performance for more accurate physics calculations, but if you have the right balance between quality and performance, then you can achieve good performance only through a proper approach.

Objects are static when they have a Collider component without a Rigidbody component. Therefore, you should not move or rotate them by changing properties in their Transform component, because it will leave a heavy imprint on your performance as a physics engine should recalculate many polygons of various objects for right collisions and ray casts. Dynamic objects are those that have a Rigidbody component. Static objects (attached with the Collider component and without Rigidbody components) can interact with dynamic objects (attached with Collider and Rigidbody components). Furthermore, static objects will not be moved by collisions like dynamic objects.

Also, Rigidbodies can sleep in order to increase performance. Unity provides the ability to control sleep in a Rigidbodies component directly in the code using following functions:

  • Rigidbody.IsSleeping()
  • Rigidbody.Sleep()
  • Rigidbody.WakeUp()

There are two variables characterized in the physics manager. You can open physics manager right from Unity menu here: Edit | Project Settings | Physics:

  • Rigidbody.sleepVelocity: The default value is 0.14. This indicates lower limitations for linear velocity (from zero to infinity) below which objects will sleep.
  • Rigidbody.sleepAngularVelocity: The default value is 0.14. This indicates lower limitations for angular velocity (from zero to infinity) below which objects will sleep.

Rigidbodies awaken when:

  • An alternate Rigidbody impacts the resting Rigidbody
  • An alternate Rigidbody was joined through a joint
  • At the point of adjusting a property of the Rigidbody
  • At the point of adding force vectors

A kinematic Rigidbody can wake the other sleeping Rigidbodies while static objects (attached with a Collider component and without a Rigidbody component) can’t wake your sleeping Rigidbodies.

The PhysX physics engine which is integrated into Unity works well on mobile devices, but mobile devices certainly have far fewer resources than powerful desktops.

Let’s look at a few points to optimize the physics engine in Unity:

  • First of all, note that you can adjust the Fixed Timestep parameter in the time manager in order to reduce costs for the physical execution time updates. If you increase the value, you can increase the quality and accuracy of physics in your game or in your application, but you will lose the time to process. This can greatly reduce your productivity, or in other words, it can increase CPU overhead.
  • The maximum allowed timestep indicates how much time will be spent in the worst case for physical treatment.
  • The total processing time for physics depends on the awake rigidbodies and colliders in the scene, as well as the level of complexity of the colliders.

Unity provides the ability to use physical materials for setting various properties such as friction and elasticity. For example, a piece of ice in your game may have very low friction or equal to zero (minimum value), while a jumping ball may have a very high friction force or equal to one (maximum value) and also very high elasticity. You should play with the settings of your physical materials for different objects and choose the most suitable solution for you and the best solution for your performance.

Triggers do not require a lot of processing costs by the physics engine and can greatly help in improving your performance. Triggers are useful in situations where, for example, in your game you need to identify areas near all lights that are automatically turned on in the evening or night if the player is in its trigger zone or in other words within the geometric shape of its collider, which you can design as you wish. Unity triggers allow writing the three callbacks, which will be called when your object enters the trigger, while your object is staying in trigger, and when this object leaves the trigger. Thus, you can register any of these functions, the necessary instructions, for example, turn on the flashlight when entering the trigger zone or turn it off when exiting the trigger zone. It is important to know that in Unity, static objects (objects without a Rigidbody component) will not cause your callbacks to get into the zone trigger if your trigger does not contain a Rigidbody component; that is, in other words at least one of these objects must have a Rigidbody component in order to not ignore your callbacks. In the case of two triggers, there should be at least one object attached with a Rigidbody component to your callbacks were not ignored. Remember that when two objects are attached with Rigidbody and Collider components and if at least one of them is the trigger, then the trigger callbacks will be called and not the collision callbacks. I would also like to point out that your callbacks will be called for each object included in the collision or trigger zone. Also, you can directly control whether your collider is a trigger or not by setting the flag isTrigger value to true or false in your code. Of course, you can mix both options in order to obtain the best performance. All collision callbacks will be called only if at least one of two interacted rigidbodies is not kinematic.

Summary

This article covered new Mecanim animation features in Unity 5. You were introduced to the new awesome audio features in Unity 5. We also covered many useful details for your performance within Unity built-in physics and particle systems.

Resources for Article:


Further resources on this subject:


Packt

Share
Published by
Packt

Recent Posts

Harnessing Tech for Good to Drive Environmental Impact

At Packt, we are always on the lookout for innovative startups that are not only…

2 months ago

Top life hacks for prepping for your IT certification exam

I remember deciding to pursue my first IT certification, the CompTIA A+. I had signed…

3 years ago

Learn Transformers for Natural Language Processing with Denis Rothman

Key takeaways The transformer architecture has proved to be revolutionary in outperforming the classical RNN…

3 years ago

Learning Essential Linux Commands for Navigating the Shell Effectively

Once we learn how to deploy an Ubuntu server, how to manage users, and how…

3 years ago

Clean Coding in Python with Mariano Anaya

Key-takeaways:   Clean code isn’t just a nice thing to have or a luxury in software projects; it's a necessity. If we…

3 years ago

Exploring Forms in Angular – types, benefits and differences   

While developing a web application, or setting dynamic pages and meta tags we need to deal with…

3 years ago