Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Unity Animation Essentials
Unity Animation Essentials

Unity Animation Essentials: Bring your characters to life with the latest features of Unity and Mecanim

eBook
$23.39 $25.99
Paperback
$26.39 $32.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Unity Animation Essentials

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

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:

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.

Rigid body animation

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.

Rigged or bone-based animation

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

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-based animation

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

Morph animation start state

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

Morph animation

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 animation

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 animation

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

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.

Animating through code – making things 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.

Animating through code – making things move

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.

Animating through code – making things move

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.

Consistent animation – speed, time, and deltaTime

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.

Movement in a direction

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.

Coding tweens with animation curves

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).

Coding tweens with animation curves

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.

Coding tweens with animation curves

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.

Coding tweens with animation curves

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.

Rotating towards objects – animation with coroutines

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).

Material and mapping animation

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.

Material and mapping animation

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

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.

Left arrow icon Right arrow icon

Description

This book is targeted at hobbyists, students, and game development professionals familiar with the Unity basics, looking to extend their skills and knowledge in the field of real-time game animation. You will need to be familiar with level design and basic scripting in C# and have a good knowledge of game development.

Who is this book for?

This book is targeted at hobbyists, students, and game development professionals familiar with the Unity basics, looking to extend their skills and knowledge in the field of real-time game animation. You will need to be familiar with level design and basic scripting in C# and have a good knowledge of game development.

What you will learn

  • Understand the latest features of Unity 5 such as state machines, meshes, and animation graphs
  • Move, transform, and change objects over time using script files
  • Use the animation editor and curve tools
  • Import and configure externally created animations for use in Unity scenes
  • See how to link animations to C# script
  • Animate cameras and create a particle system
  • Produce sophisticated sprite animations for both 2D and 3D games
  • Apply more advanced workflows and techniques to refine character animations
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 24, 2015
Length: 200 pages
Edition : 1st
Language : English
ISBN-13 : 9781782174813
Vendor :
Unity Technologies
Languages :
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Jun 24, 2015
Length: 200 pages
Edition : 1st
Language : English
ISBN-13 : 9781782174813
Vendor :
Unity Technologies
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 109.57 136.97 27.40 saved
Unity Animation Essentials
$26.39 $32.99
Unity 5.x Animation Cookbook
$39.19 $48.99
Unity Character Animation with Mecanim
$43.99 $54.99
Total $ 109.57 136.97 27.40 saved Stars icon

Table of Contents

8 Chapters
1. Animation Fundamentals Chevron down icon Chevron up icon
2. Sprite Animation Chevron down icon Chevron up icon
3. Native Animation Chevron down icon Chevron up icon
4. Noncharacter Animation with Mecanim Chevron down icon Chevron up icon
5. Character Animation Fundamentals Chevron down icon Chevron up icon
6. Advanced Character Animation Chevron down icon Chevron up icon
7. Blend Shapes, IK, and Movie Textures Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8
(10 Ratings)
5 star 50%
4 star 20%
3 star 0%
2 star 20%
1 star 10%
Filter icon Filter
Top Reviews

Filter reviews by




mactabs Jul 18, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is my first book by Alan Thorn; I primarily learned about him through his old video tutorials in Unity. Like those other materials he has given straightforward and easy to follow instructions on utilizing Unity, this time regarding animations. Another plus for the book is that it covers the latest version, Unity 5, but you can still use it for Unity 4x which includes Mechanim. The sample code provided on the Packt website may be very large but it is advised to download it to really appreciate the lessons that you can get from this.
Amazon Verified review Amazon
Leslie Harback May 13, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I don't have a tremendously long review to contribute-- this is a helpful, extremely concise book that deals with various types of Unity animation in a very cursory way. But it's cursory in a compelling, to-the-point way. I primarily picked the book up for help learning Mecanim, and it provides a much more well-written and informative introduction to the subject than the other Packt Unity animation book, 'Unity Character Animation with Mecanim'.But when I say short, it's shockingly so-- I was able to work through the whole book in an afternoon. At the end though, I had a pretty decent starting point from which to keep on learning on the subject.Again, since folks care about these things and I'm not sure it's really discussed in the description, all code examples in the book are in C#.
Amazon Verified review Amazon
Anonymous Jan 29, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I am fairly new to Unity (full time for just a few months) but have decided to make a personal goal of learning as much as I can over the next few months to see its potential. I have been working on a 2D game for a friend's company, and often got confused as to what capabilities Unity offered for 2D versus 3D in regards to animations. I have gone through many online articles and videos but still had some questions unresolved. I ordered this book since it focused solely on this topic, in hopes that it would clear up some of the confusion.The author has a very easy to read writing style. IN fact, I read through the entire book the same day I got it. I had already learned a lot of the material through my own research, but the book did clarify many things and presented some things I didn't know. I was very pleased to see the section near the end on blend trees which was another source of confusion for me until now.Having over 20 years of IT experience, I am fairly good at judging technical books. I believe this book is ideal for beginner to intermediate Unity programmers who want to better understand how animations work in Unity. The writer's style seems to fit those readers in particular. I am currently in the middle of another book by same author (Mastering Unity Scripting) which appears to be even better. I will write a review on that one soon.
Amazon Verified review Amazon
Michael Jul 15, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Alan Thorn has quickly become my favorite Unity author. I have purchased four Unity books developed and written by him including this one. Alan's instructional style and easy to follow projects actually teach me something, unlike others who say, "do this" and "do that" without explaining why and when to use a particular function in Unity. Alan takes the time to explain the "why" and "when" in easy to understand language. The sample files provided at the PackT is large, but well worth it! This book walks you through the fundamentals of animation, including sprite (2D) animation; plus, chapters on the fundamentals of mecanim and character animation. I highly recommend this book for anyone interested in learning animation within Unity. In fact, I recommend any of Alan Thorn's books on Unity programming.ALSO, PackT books transfer nicely to the Kindle and Kindle Apps.
Amazon Verified review Amazon
Cherno Olivares Oct 14, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Una buena introducción a los sistemas de animación disponibles en Unity, merece la pena comprarlo. He visto bastantes libros y es el único que me ha ayudado, claro, conciso y directo.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
Modal Close icon
Modal Close icon