Home Business & Other Unity Animation Essentials

Unity Animation Essentials

By Alan Thorn
books-svg-icon Book
eBook $25.99 $17.99
Print $32.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $25.99 $17.99
Print $32.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
About this book
Publication date:
June 2015
Publisher
Packt
Pages
200
ISBN
9781782174813

 

Chapter 1. Animation Fundamentals

Greetings and welcome to this journey through the animation feature set in the world of Unity. The importance of animation cannot be understated. Without animation, everything in-game would be statuesque, lifeless and perhaps boring. This holds true for nearly everything in games: doors must open, characters must move, foliage should sway with the wind, sparkles and particles should explode and shine, and so on. Consequently, learning animation and how to animate properly will unquestionably empower you as a developer, no matter what your career plans are. As a subject, animation creeps unavoidably into most game fields, and it's a critical concern for all members of a team—obviously for artists and animators, but also for programmers, sound designers, and level designers. This book is both valuable and relevant for most developers, and it aims to quickly and effectively introduce the fundamental concepts and practices surrounding animation in real-time games, specifically animation in Unity. By the end of this book, if you read each chapter carefully in order, you'll gain solid knowledge and a skill set in animation. You will be capable of making effective animations that express your artistic vision, as well as gaining an understanding of how and where you can expand your knowledge to the next level. But to reach that stage we'll begin here, in Chapter 1, with the most basic concepts of animation—the groundwork for any understanding of animation.

 

Understanding animation


At its most fundamental level, animation is about a relationship between two specific and separate properties, namely change on one hand and time on the other. Technically, animation defines change over time, that is, how a property adjusts or varies across time, such as how the position of a car changes over time, or how the color of a traffic light transitions over time from red to green. Thus, every animation occurs for a total length of time (duration), and throughout its lifetime, the properties of the objects will change at specific moments (frames), anywhere from the beginning to the end of the animation.

This definition is itself technical and somewhat dry, but relevant and important. However, it fails to properly encompass the aesthetic and artistic properties of animation. Through animation and through creative changes in properties over time, moods, atmospheres, worlds, and ideas can be conveyed effectively. Even so, the emotional and artistic power that comes from animation is ultimately a product of the underlying relationship of change with time. Within this framework of change over time, we may identify further key terms, specifically in computer animation. You may already be familiar with these concepts, but let's define them more formally.

Frames

Within an animation, time must necessarily be divided into separate and discrete units where change can occur. These units are called frames. Time is essentially a continuous and unbreakable quantity, insofar as you can always subdivide time (such as a second) to get an even smaller unit of time (such as a millisecond), and so on. In theory, this process of subdivision could essentially be carried on ad infinitum, resulting in smaller and smaller fractions of time. The concept of a moment or event in time is, by contrast, a human-made, discrete, and self-contained entity. It is a discrete thing that we perceive in time to make our experience of the world more intelligible. Unlike time, a moment is what it is, and it cannot be broken down into something smaller without ceasing to exist altogether. Inside a moment, or a frame, things can happen. A frame is an opportunity for properties to change—for doors to open, characters to move, colors to change, and more. In video game animation specifically, each second can sustain or contain a specified number of frames. The amount of frames passing within a second will vary from computer to computer, depending on the hardware capacity, the software installed, and other factors. The frame capacity per second is called FPS (frames per second). It's often used as a measure of performance for a game, since lower frame rates are typically associated with jittery and poor performance. Consider the following figure, showing how frames divide time:

Frames divide time

Key frames

Although a frame represents an opportunity for change, it doesn't necessarily mean change will occur. Many frames can pass by in a second, and not every frame requires a change. Moreover, even if a change needs to happen for a frame, it would be tedious if animators had to define every frame of action. One of the benefits of computer animation, contrasted with manual, or "old", animation techniques, is that it can make our lives easier. Animators can instead define key, or important, frames within an animation sequence, and then have the computer automatically generate the intervening frames. Consider a simple animation in which a standard bedroom door opens by rotating outwards on its hinges by 90 degrees. The animation begins with the door in the closed position and ends in an open position. Here, we have defined two key states for the door (open and closed), and these states mark the beginning and end of the animation sequence. These are called key frames, because they define key moments within the animation. On the basis of key frames, Unity (as we'll see) can autogenerate the in-between frames (tweens), smoothly rotating the door from its starting frame to its ending frame. The mathematical process of generating tweens is termed as interpolation. See the following figure, showing how frames are generated between key frames:

Tweens are generated between key frames using interpolation

 

Animation types


The previous section defined the core concepts underpinning animation generally. Specifically, it covered change, time, frames, key frames, tweens, and interpolation. On the basis of this, we can identify several types of animation in video games from a technical perspective, as opposed to an artistic one. All variations depend on the concepts we've seen, but they do so in different and important ways. These animation types are significant for Unity because the differences in their nature require us to handle and work with them differently, using specific workflows and techniques that we will cover in the upcoming chapters. The animation types are listed throughout this section, as follows.

Rigid body animation

Rigid body animation is used to create pre-made animation sequences that move or change the properties of objects, considering those objects as whole or complete entities, as opposed to objects with smaller and moving parts. Some examples of this type of animation are a car racing along the road, a door opening on its hinges, a spaceship flying through space on its trajectory, and a piano falling from the side of a building. Despite the differences among these examples, they all have an important common ingredient. Specifically, although the object changes across key frames, it does so as a single and complete object. In other words, although the door may rotate on its hinges from a closed state to an open state, it still ends the animation as a door, with the same internal structure and composition as before. It doesn't morph into a tiger or a lion. It doesn't explode or turn into jelly. It doesn't melt into rain drops. Throughout the animation, the door retains its physical structure. It changes only in terms of its position, rotation and scale. Thus, in rigid body animation, changes across key frames apply to whole objects and their highest level properties. They do not filter down to subproperties and internal components, and they don't change the essence or internal forms of objects. These kinds of animation can be defined either directly in the Unity animation editor, as we'll see in later chapters, or inside 3D animation software (such as Maya, Max, or Blender) and then imported to Unity through mesh files. Chapter 3, Native Animation, covers rigid body animation further.

Key frame animation for rigid bodies

Rigged or bone-based animation

If you need to animate human characters, animals, flesh-eating goo, or exploding and deforming objects, then rigid body animation probably won't be enough. You'll need bone-based animation (also called rigged animation). This type of animation changes not the position, rotation, or scale of an object, but the movement and deformation of its internal parts across key frames. It works like this: the animation artist creates a network of special bone objects to approximate the underlying skeleton of a mesh, allowing independent and easy control of the surrounding and internal geometry. This is useful for animating arms, legs, head turns, mouth movements, tree rustling, and a lot more. Typically, bone-based animation is created as a complete animation sequence in 3D modeling software and is imported to Unity inside a mesh file, which can be processed and accessed via Mecanim, the Unity animation system. Chapters 5, 6, and 7 cover bone-based animation in greater detail.

Bone-based animation is useful for character meshes

Sprite animation

For 2D games, graphical user interfaces, and a variety of special effects in 3D (such as water textures), you'll sometimes need a standard quad or plane mesh with a texture that animates. In this case, neither the object moves, as with rigid body animation, nor do any of its internal parts change, as with rigged animation. Rather, the texture itself animates. This animation type is called sprite animation. It takes a sequence of images or frames and plays them in order at a specified frame rate to achieve a consistent and animated look, for example, a walk cycle for a character in a 2D side-scrolling game. More information on sprite animation is given in the next chapter.

Sprite animation

Physics-based animation

In many cases, you can predefine your animation. That is, you can fully plan and create animation sequences for objects that will play in a predetermined way at runtime, such as walk cycles, sequences of door opening, explosions, and others. But sometimes, you need animation that appears realistic and yet responds to its world dynamically, based on decisions made by the player and other variable factors of the world that cannot be predicted ahead of time. There are different ways to handle these scenarios, but one is to use the Unity physics system, which includes components and other data that can be attached to objects to make them behave realistically. Examples of this include falling to the ground under the effects of gravity, and bending and twisting like cloth in the wind.

Physics animation

Tip

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.

Morph animation

Occasionally, none of the animation methods you've read so far—rigid body, physics-based, rigged, or sprite animation—give you what's needed. Maybe, you need to morph one thing into another, such as a man into a werewolf, a toad into a princess, or a chocolate bar into a castle. In some instances, you need to blend, or merge smoothly, the state of a mesh in one frame into a different state in a different frame. This is called morph animation, or blend shapes. Essentially, this method relies on snapshots of a mesh's vertices across key frames in an animation, and blends between the states via tweens. The downside to this method is its computational expense. It's typically performance intensive, but its results can be impressive and highly realistic. We'll see blend shapes in detail later in Chapter 7, Blend Shapes, IK, and Movie Textures. See the following screenshot for the effects of blend shapes:

Morph animation start state

BlendShapes transition a model from one state to another. See the following figure for the destination state:

Morph animation end state

Video animation

Perhaps one of Unity's lesser known animation features is its ability to play video files as animated textures on desktop platforms and full-screen movies on mobile devices such as iOS and Android devices. Unity accepts OGV (Ogg Theora) videos as assets, and can replay both videos and sounds from these files as an animated texture on mesh objects in the scene. This allows developers to replay pre-rendered video file output from any animation package directly in their games.

This feature is powerful and useful, but also performance intensive. Chapter 7, Blend Shapes, IK, and Movie Textures, describes video animation in more depth.

Video file animation

Particle animation

Most animation methods considered so far are for clearly defined, tangible things in a scene, such as sprites and meshes. These are objects with clearly marked boundaries that separate them from other things. But you'll frequently need to animate less tangible, less solid, and less physical matter, such as smoke, fire, bubbles, sparkles, smog, swarms, fireworks, clouds, and others. For these purposes, a particle system is indispensable. As we'll see in Chapter 3, Native Animation, particle systems are entirely configurable objects that can be used to simulate rain, snow, flock of birds, and more. See the following screenshot for a particle system in action:

Particle system animation

Programmatic animation

Surprisingly, the most common animation type is perhaps programmatic animation, or dynamic animation. If you need a spaceship to fly across the screen, a user-controlled character to move around an environment, or a door to open when approached, you'll probably need some programmatic animation. This refers to changes made to properties in objects over time, which arise because of programming—code that a developer has written specifically for that purpose. Unlike many other forms of animation, the programmatic form is not created or built in advance by an artist or animator per se, because its permutations and combinations cannot be known upfront. So, it's coded by a programmer and has the flexibility to change and adjust according to conditions and variables at runtime. Of course, in many cases, animations are made by artists and animators and the code simply triggers or guides the animation at runtime. You'll learn more on programmatic animation in subsequent sections of this chapter.

Programmatic animation is controlled through script

 

Animating through code – making things move


Animating through code is a great way to start animating generally, as it demonstrates all the core concepts we've seen so far, so let's try it. For this section, and the remaining sections, we'll use C# for scripting wherever applicable. However, since this book focuses on animation, I won't be explaining basic coding concepts here (such as variables, loops, and functions). Instead, I'll assume you already have basic to intermediate coding knowledge. If you want to learn coding, I recommend my 3dmotive video course C# For Unity Developers (available at http://3dmotive.com/) and Learning C# by Developing Games with Unity 3D Beginner's Guide, Packt Publishing.

By the end of the next few sections, we'll have created a game object (for example, a spaceship) that can travel at a constant speed in a single direction across the level. To get started, create a new script file by right-clicking inside the Project panel. Go to Create | C# Script from the context menu. Alternatively, go to Assets | Create | C# Script from the application menu, as shown in the following screenshot. Name the file Mover.cs. This script will be attached to any object that will move.

Now open the script file in MonoDevelop by double-clicking on it from the Project panel. By default, all new scripts are created with two functions: Start and Update. The Update function is of special significance for animation because it's related to frames and the frame rate. Specifically, it's called on every frame at runtime. This means that for a game with an FPS of 70, the Update function is called 70 times per second for each object with the script attached, provided the object is active. This makes Update important for animation because it gives us an opportunity to adjust an object's properties continually over time.

The Update function is called once per frame

To start moving an object, let's code the Update function, as shown in the following snippet. It accesses the object's transform component and increments its current position in the x axis by 1 unit (meter) on each frame.

Code sample 1-1: moving an object:

using UnityEngine;
using System.Collections;

public class Mover : MonoBehaviour 
{
  // Use this for initialization
  void Start () {
  
  }
  
  // Update is called once per frame
  void Update () 
  {
    //Transform component on this object
    Transform ThisTransform = GetComponent<Transform>();

    //Add 1 to x axis position
    ThisTransform.position += new Vector3(1f,0f,0f);
  }
}

If you haven't already tested the code, drag and drop the script file onto an object in the scene. Then press the Play button. Depending on your view, the object may move too fast to be visible. Be sure to position your camera for a good view, and you should see your object spring to life by moving continually on the x axis.

Adding the Mover script to an object in the scene

Consistent animation – speed, time, and deltaTime

The code in sample 1-1 works, but there's an important animation problem, and we should address it directly. As we've seen, the object travels along the x axis by 1 unit on every call to Update, that is, on each frame. This is potentially a problem because frame rates differ across computers, and even over time on the same computer. This means that different users will get different experiences while using our code because the object will move at varying speeds. Specifically, on a system with an FPS of 70, the object will be updated by 70 units every second. But on a different system running at 90 FPS, the object will move 90 units in the same time. This is bad, because we want all users to get a consistent in-game experience, experiencing time at the same speed and in the same way. This issue is especially important for multiplayer games, where it's critical that all users are in sync. To solve this issue, we need to approach the task differently, thinking in terms of speed and time.

To calculate how far an object should travel over time, we can use the speed-distance-time formula, where distance traveled = speed x time. This means that an object traveling at 10 meters per second for 5 seconds will travel a total of 50 meters. This way of thinking about movement doesn't rely on frame rates and frames. Also, it doesn't link motion to the Update function and its frequency specifically. Instead it maps motion to time directly, and time is consistent across all computers; that is, 1 second is the same everywhere. To code this in Unity, we can use the deltaTime variable. Consider code sample 1-2, which updates and improves on code sample 1-1.

Code sample 1-2: setting an object's speed:

using UnityEngine;
using System.Collections;

public class Mover : MonoBehaviour 
{
  //Amount to travel (in metres) per second
  public float Speed = 1f;
  
  // Update is called once per frame
  void Update () 
  {
    //Transform component on this object
    Transform ThisTransform = GetComponent<Transform>();

    //Update X Axis position by 1 metre per second
    ThisTransform.position += new Vector3(Speed * Time.deltaTime,0f,0f);
  }
}

The deltaTime variable is a native Unity variable updated every frame, and is part of the Time class. On each frame, it expresses (in seconds) how much time has elapsed since the previous frame. Therefore, if deltaTime is 0.5, then it means 1/2 of a second has elapsed since the previous frame, that is, since the Update function was last called. This is highly important information because, when multiplied by speed values, we always scale the speed value to be consistent with the frame rate for the current computer, ensuring a consistent speed across computers. By doing this, we make all speed values work the same for everybody. Now try this code in the editor and see the difference. Our objects will now move at the same speed on all computers.

Press Play and test the new code

Movement in a direction

Based on code sample 1-2, we now have an object that moves in the x axis at a consistent speed. But how can the code be adapted to move in a different direction? If we wanted to move in only the y or z direction, we could've adapted the code easily. But what about movement in any arbitrary direction, including diagonals? For this, we need vectors. A vector is a three-component number in the form of (x, y, z), representing a direction. For example, (0, 1, 0) means up (since the up-down axis is y) and (0, 0, 1) means forward (since the z axis represents the forward-backward axis).

Code sample 1-3: controlling the direction:

using UnityEngine;
using System.Collections;

public class Mover : MonoBehaviour 
{
  //Amount to travel (in metres) per second
  public float Speed = 1f;

  //Direction to travel
  public Vector3 Direction = Vector3.zero;
  
  // Update is called once per frame
  void Update () 
  {
    //Transform component on this object
    Transform ThisTransform = GetComponent<Transform>();

    //Update position in specified direction by speed
    ThisTransform.position += Direction.normalized * Speed * Time.deltaTime;
  }
}

Now return to your object in the scene. The object inspector shows a Direction variable that can be edited to specify the direction in which the object should move. Movement along the x axis is due to (1, 0, 0) or (-1, 0, 0), and the numbers are similar for the other axes. You can also travel in diagonals using (1, 1, 1), which means moving in all three axes simultaneously.

Specifying a direction for the Mover script

Note

The Unity project for this assignment can be found in this book's companion files in the Chapter01/Moving Object folder.

Coding tweens with animation curves

For objects that move continually at a constant speed and in a straight line, the code created in sample 1-3 works exactly as expected. But when animating, you'll typically want objects to move along curved paths, not just straight paths. Or you'd want objects to travel at variable speeds as opposed to constant speeds. To solve this, we can use animation curves, which are special objects (available only in Unity Pro) that allow us to build curves that define tweens for the animation, controlling how an object changes across key frames. Consider code sample 1-4, which allows us to vary an object's speed over time with an animation curve.

Note

More information on animation curves can be found online at http://docs.unity3d.com/Manual/animeditor-AnimationCurves.html.

Code sample 1-4: ramping the speed:

using UnityEngine;
using System.Collections;

public class Mover : MonoBehaviour 
{
  //Maximum Speed to travel (in metres) per second
  public float Speed = 1f;
  
  //Direction to travel
  public Vector3 Direction = Vector3.zero;

  //Curve to adjust speed
  public AnimationCurve AnimCurve;

  // Update is called once per frame
  void Update () 
  {
    //Transform component on this object
    Transform ThisTransform = GetComponent<Transform>();

    //Update position in specified direction by speed
ThisTransform.position += Direction.normalized * Speed * AnimCurve.Evaluate(Time.time) * Time.deltaTime;
  }
}

With the code in sample 1-4, select the animated object in the scene and examine the object inspector. The public AnimCurve variable is now visible as a graph.

Accessing the animation curve editor

Click on the graph in the inspector to show the graph editor as a separate dialog. This graph allows you to control the tweens applied to the speed value. The horizontal axis represents time (in seconds), and the vertical axis represents the value (speed).

Building an animation curve

You can click any of the bottom-left curve presets to generate an initial curve, controlling interpolation for object speed. You can also double-click anywhere along the curve to insert new control points, allowing greater control of the curve's shape. Let's go ahead and create a famous type of curve in animation—an ease-in-ease-out curve. It will gradually increase the object's speed at the start of the animation (acceleration), and then eventually reduce the object's speed towards a complete stop (deceleration). To start, use the mouse's scrolling wheel to zoom out from the curve view, to show a horizontal view of 5 seconds in all from 0 seconds at animation start to 5 seconds at animation end. Make sure that the first and last key frame points rest at the start and end times respectively on the horizontal axis. Also make sure that both the points are at 0 for the vertical axis, which means that the object's speed should be 0 at both the start and the end.

Tip

As you click and drag the points, hold down the Ctrl key to snap to grid.

Starting an animation curve

To build an ease-in-ease-out curve, insert a new control point at the curve's center (at time equal to 2.5 seconds), and drag it upward on the vertical axis to a value of 1, representing the maximum speed for the object at that time. If the new control point forms a hard-edged angle in the curve, preventing it from being smooth, then right-click on the control point and select the Free Smooth option from the context menu to smooth out the curve.

Tip

You can press F to resize the graph view to get the curve fully in view.

Creating an ease-in-ease-out curve for speed

Once the curve is constructed, give the code a test run by playing the Unity project, and see the effect it has in the Game tab. Based on code sample 1-4, the speed of the object will necessarily animate according to the curve over time. The AnimationCurve.Evaluate method accepts a time value as the input (on the horizontal axis) and returns an associated value from the y axis as a multiplier for speed. Using this function, we can evaluate any curve for programmatic animation.

Note

More information on the Evaluate method can be found at the official Unity documentation at http://docs.unity3d.com/ScriptReference/AnimationCurve.html.

The Unity project for this assignment can be found in this book's companion files in the Chapter01/animation_curves folder.

Rotating towards objects – animation with coroutines

Now let's try a different programmatic animation scenario using coroutines, a special kind of function that are very useful for creating types of behavior that unfold over time. Specifically, we'll create a script that slowly and smoothly rotates an object to always face its target. This is useful for building enemies that always turn to look at you, rotating gun turrets, or other objects that must track a target. It should be emphasized here that the intended behavior isn't simply the LookAt behavior, which causes objects to immediately be oriented towards a target using the Transform.LookAt function. Instead, we're coding a kind of behavior in which an object always rotates at a specified angular speed to face a target, as shown in the following screenshot. The object may or may not be looking at its target at a particular moment, but it'll always be trying to look at it. This involves rotation and turning over time to look at its target, wherever the latter moves. Consider the code file (LookAt.cs) in sample 1-5.

A cubical object rotating to face a sphere

Note

More information on coroutines can be found in the Unity official documentation at http://docs.unity3d.com/Manual/Coroutines.html.

Code sample 1-5: rotating to face a target:

//--------------------------------------------
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
//--------------------------------------------
public class LookAt : MonoBehaviour
{
  //Cached transform
  private Transform ThisTransform = null;

  //Target to look at
  public Transform Target = null;

  //Rotate speed
  public float RotateSpeed = 100f;

  //--------------------------------------------
  // Use this for initialization
  void Awake () {
    //Get transform for this object
    ThisTransform = GetComponent<Transform>();
  }
  //--------------------------------------------
  void Start()
  {
    //Start tracking target
    StartCoroutine(TrackRotation(Target));
  }
  //--------------------------------------------
  //Coroutine for turning to face target
  IEnumerator TrackRotation(Transform Target)
  {
    //Loop forever and track target
    while(true)
    {
      if(ThisTransform != null && Target != null)
      {
        //Get direction to target
        Vector3 relativePos = Target.position - ThisTransform.position;

        //Calculate rotation to target
        Quaternion NewRotation = Quaternion.LookRotation(relativePos);

        //Rotate to target by speed
        ThisTransform.rotation = Quaternion.RotateTowards(ThisTransform.rotation, NewRotation, RotateSpeed * Time.deltaTime);
      }

      //wait for next frame
      yield return null;
    }
  }
  //--------------------------------------------
  //Function to draw look direction in viewport
  void OnDrawGizmos()
  {
    Gizmos.DrawLine(ThisTransform.position, ThisTransform.forward.normalized * 5f);
  }
  //--------------------------------------------
}
//--------------------------------------------

Coroutines work differently from regular functions. They always feature an IEnumerator return type and contain at least one yield statement. Unlike regular functions, which perform their work line by line and then terminate, after which program execution resumes, coroutines seem to run in parallel with the process that invoked them. They feel and work much like a thread or background process—though without truly being so—multitasking and running alongside other processes. This makes them useful for animation, allowing us to animate and change properties for objects while other processes are running.

Note

The Unity project for this assignment can be found in this book's companion files in the Chapter01/RotatingObjects folder.

Material and mapping animation

Another really useful animation technique is UV or mapping animation, as shown in the following screenshot. This involves programmatically tweaking or changing the UV coordinates across a mesh's vertices over time to slide or move around the texture on its surface. This doesn't change or alter the pixels inside the texture itself, but rather animates where the pixels are mapped on the surface. Using UV animation, various effects can be created, such as animated water, flowing lava, moving clouds, warp tunnel effects, and lots more. Consider code sample 1-6 (MatScroller.cs).

Animating texture mapping for a surface to create moving clouds, water, or lava

Code sample 1-6: material scroller:

//CLASS TO SCROLL TEXTURE ON PLANE. CAN BE USED FOR MOVING SKY
//------------------------------------------------
using UnityEngine;
using System.Collections;
//------------------------------------------------
[RequireComponent (typeof (MeshRenderer))] //Requires Renderer Filter Component
public class MatScroller : MonoBehaviour
{
  //Public variables
  //------------------------------------------------
  //Reference to Horizontal Scroll Speed
  public float HorizSpeed = 1.0f;
  
  //Reference to Vertical Scroll Speed
  public float VertSpeed = 1.0f;
  
  //Reference to Min and Max Horiz and Vertical UVs to scroll between
  public float HorizUVMin = 1.0f;
  public float HorizUVMax = 2.0f;
  
  public float VertUVMin = 1.0f;
  public float VertUVMax = 2.0f;
  
  //Private variables
  //------------------------------------------------
  //Reference to Mesh Renderer Component
  private MeshRenderer MeshR = null;

  //Methods
  //------------------------------------------------
  // Use this for initialization
  void Awake ()
  {
    //Get Mesh Renderer Component
    MeshR = GetComponent<MeshRenderer>();
  }
  //------------------------------------------------
  // Update is called once per frame
  void Update () 
  {
    //Scrolls texture between min and max
    Vector2 Offset = new Vector2((MeshR.material.mainTextureOffset.x > HorizUVMax) ? HorizUVMin : MeshR.material.mainTextureOffset.x + Time.deltaTime * HorizSpeed,
                   (MeshR.material.mainTextureOffset.y > VertUVMax) ? VertUVMin : MeshR.material.mainTextureOffset.y + Time.deltaTime * VertSpeed);
    
    //Update UV coordinates
    MeshR.material.mainTextureOffset = Offset;
  }
  //------------------------------------------------
}
//------------------------------------------------

This code can be attached to a mesh object to animate its material. Simply set the HorizSpeed and VertSpeed variables from the object inspector to control the horizontal and vertical scroll speeds of the material.

Controlling a material's scroll speed

Note

The Unity project for this assignment can be found in this book's companion files in the Chapter01/texture_animator folder.

Camera shaking – animation effects

The camera shake effect

If you've played hard-hitting action games, such as beat 'em ups or shooters, you'll often see a camera shake effect when the characters get hurt. The shake effect adds a dramatic impact and dynamism to the action. It's also a really easy animation effect to achieve, based only on the principles and ideas we've already seen in this chapter. Consider code sample 1-7, which may be added to any scene camera to create a shake effect:

Code sample 1-7: camera shake:

using UnityEngine;
using System.Collections;
//---------------------
public class CameraShake : MonoBehaviour 
{
  private Transform ThisTransform = null;

  //Total time for shaking in seconds
  public float ShakeTime = 2.0f;

  //Shake amount - distance to offset in any direction
  public float ShakeAmount = 3.0f;

  //Speed of camera moving to shake points
  public float ShakeSpeed = 2.0f;

  //---------------------
  // Use this for initialization
  void Start () 
  {
    //Get transform component
    ThisTransform = GetComponent<Transform>();

    //Start shaking
    StartCoroutine(Shake());
  }
  //---------------------
  //Shake camera
  public IEnumerator Shake()
  {
    //Store original camera position
    Vector3 OrigPosition = ThisTransform.localPosition;

    //Count elapsed time (in seconds)
    float ElapsedTime = 0.0f;

    //Repeat for total shake time
    while(ElapsedTime < ShakeTime)
    {
      //Pick random point on unit sphere
      Vector3 RandomPoint = OrigPosition + Random.insideUnitSphere * ShakeAmount;

      //Update Position
      ThisTransform.localPosition = Vector3.Lerp(ThisTransform.localPosition, RandomPoint, Time.deltaTime * ShakeSpeed);

      //Break for next frame
      yield return null;

      //Update time
      ElapsedTime += Time.deltaTime;
    }

    //Restore camera position
    ThisTransform.localPosition = OrigPosition;
  }
  //---------------------
}
//---------------------

This code sample uses coroutines to fluctuate the position of the camera randomly over time within an imaginary spherical volume using the Random.insideUnitSphere variable. To use this code, just drag and drop the script onto a camera, and go!

Note

The Unity project for this assignment can be found in this book's companion files in the Chapter01/camera_shake folder.

 

Summary


This chapter considered animation abstractly, as a form of art, and as a science. We covered the types of animation that are most common in Unity games. In addition, we examined some core tasks and ideas in programmatic animation, including the ability to animate and change objects dynamically through code without relying on pre-scripted or predefined animations, which will engross you in much of this book. Although this chapter marks the end of our coverage of programmatic animation (at least in a dedicated way), coding and scripts will nevertheless find an important niche and presence throughout most of the upcoming chapters. The next chapter continues our journey, with us entering the world of 2D animation for sprites.

About the Author
  • Alan Thorn

    Alan Thorn is a multidisciplinary game developer, author, and educator with 16 years of industry experience. He makes games for PC desktop, mobile, and VR. He founded 'Wax Lyrical Games' and created the award-winning game Baron Wittard: Nemesis of Ragnarok, working as a designer, programmer, and artist. He has written 20 technical books on game development and presented fifteen video training courses. These cover gameplay programming, Unity development, 3D modelling, and animation. He has worked in game development education as a visiting lecturer for the National Film and Television School, as a lead teacher for Uppingham School, and as a senior lecturer at Teesside University.

    Browse publications by this author
Latest Reviews (1 reviews total)
Unity Animation Essentials
Unlock this book and the full library FREE for 7 days
Start now