Animation With Timers

Last time I talked about using timers for scheduling events by simply keeping track of a time limit and how much time elapsed. Another good use for timers is performing some action over time, such as modifying alpha to fade an object in or out, or sliding an object from one location to another.

Let’s use the fading example. Fading is often done by animating transparency. The object starts out completely transparent, and gradually becomes less transparent until it’s fully opaque. An object is fully transparent when it’s drawn using alpha blending with an alpha of zero, and fully opaque when alpha is one. By quickly changing alpha from 0 to 1 over time, and redrawing the object  with the new alpha, it appears to fade into view.

You might say that when alpha is 0 the object is 0% visible, and when alpha is 1 it’s 100% visible. Thinking about the starting and ending values as percentages is very useful. For example, If you’re moving an object from one position to another, the object hasn’t moved at all at 0%, it’s moved halfway at 50%, and it’s moved all the way at 100%.  Another example, if you’re fading in a song, it’s completely silent at 0% volume, it’s medium loudness at 50% volume, and it’s full volume at 100%. Being able to animate a value from 0 to 1 has all kinds of applications in a video game.

So we need to be able to animate a value from 0 to 1, and we want it to take a specified amount of time. In the last post we already made a timer that can run for a specified amount of time.

In that timer, the variable Elapsed keeps track of how much time has elapsed since the timer started. Elapsed starts out at 0, and as the timer runs it progresses to Limit, which is when the timer expires. Looking at it another way, Elapsed has progressed 0% when it starts, and 100% when it ends. In order to calculate the progress as a percentage, we simply divide Elapsed by Limit.

Let’s change the SimpleTimer class so it calculates this percentage for us. We’ll save it in a field called Time. Here’s the class as it stood at the end of the last post.

public class SimpleTimer
{
  public float Limit;
  public float Elapsed;

  public SimpleTimer(float limit)
  {
    Limit = limit;
    Stop(); // make sure it's not running
  }

  public void Start()
  {
    Elapsed = 0.0f;
  }

  public void Stop()
  {
    Elapsed = -1.0f;
  }

  public bool Update(float elapsedTime)
  {
    bool result = false;

    if (Elapsed >= 0.0f)
    {
      Elapsed += elapsedTime;
      result = Elapsed >= Limit;
    }

    return result;
  }
}

First, add our Time field right after Elapsed:

public float Limit;
public float Elapsed;
public float Time;    // <-- add this

Next, add an UpdateTime method that does the percentage calculation and saves it to the Time field:

private void UpdateTime()
{
  Time = Elapsed / Limit;
}

Now, every time we modify Elapsed we need to call UpdateTime so Time is recalculated. We set Elapsed to 0 in the Start method, so we need an UpdateTime call there:

public void Start()
{
  Elapsed = 0.0f;
  UpdateTime();  // <-- add this
}

We also modify Elapsed in the Update method:

if (Elapsed >= 0.0f)
{
  Elapsed += elapsedTime;
  result = Elapsed >= Limit;
  UpdateTime();  // <-- add this
}

And that’s it.  Here’s the full class:

public class SimpleTimer
{
  public float Limit;
  public float Elapsed;
  public float Time;

  public SimpleTimer(float limit)
  {
    Limit = limit;
    Stop();
  }
  public void Start()
  {
    Elapsed = 0.0f;
    UpdateTime();
  }
  public void Stop()
  {
    Elapsed = -1.0f;
  }
  private void UpdateTime()
  {
    Time = Elapsed / Limit;
  }
  public bool Update(float elapsedTime)
  {
    bool result = false;
    if (Elapsed >= 0.0f)
    {
      Elapsed += elapsedTime;
      result = Elapsed >= Limit;
      UpdateTime();
    }
    return result;
  }
}

Now, as our timer is running, it’s always calculating how far it’s gone towards Limit as a percentage, which gives us a value between 0 and 1.  If we’re animating something like alpha that already takes a value between 0 and 1 then we can just use Time directly. But what if we need to change from one color to another, or move an object from one position on the screen to another?

This is where interpolation comes into play. The dictionary defines interpolation as “the process of determining the value of a function between two points at which it has prescribed values”. The “prescribed values” are our starting and ending colors, or our starting and ending positions. There are multiple ways to do the interpolation depending on your needs. A common one is Linear Interpolation, and that’s what we’ll use here. I’m just going to describe a couple of methods supplied by the XNA framework. If you want to learn how linear interpolation works you should be able to find the information on the web pretty easily.

XNA provides several Lerp (Linear intERPolation) methods:

MathHelper.Lerp
Vector2.Lerp
Vector3.Lerp
Matrix.Lerp
Color.Lerp
Quaternion.Lerp

Each of these takes starting and ending values of the appropriate data type, an amount value between 0 and 1, and returns a new value that’s amount percent between the starting and ending values. For example, MathHelper.Lerp performs linear interpolation on float values. Here are some sample values and what the function returns:

MathHelper.Lerp(10, 20, 0.0f);  // returns 10
MathHelper.Lerp(10, 20, 0.2f);  // returns 12
MathHelper.Lerp(10, 20, 0.5f);  // returns 15
MathHelper.Lerp(10, 20, 0.8f);  // returns 18
MathHelper.Lerp(10, 20, 1.0f);  // returns 20

To move an object you can use the Vector2.Lerp method and pass in Time from our timer class as amount. In this example position will start at <50, 50> and work its way in a straight line towards <750, 400> as timer.Time changes from 0 to 1.

Vector2 start = new Vector2(50, 50);
Vector2 end = new Vector2(750, 400);
Vector2 position = Vector2.Lerp(start, end timer.Time);

Similarly, color can be interpolated between two values like this:

color = Color.Lerp(Color.CornflowerBlue, Color.White, timer.Time);

I’ve included a sample project that contains the timer class as well as a simple demonstration that moves a square across the screen and cycles colors using the timer and linear interpolation.

There are many more useful things you can add to your timers, such as pausing, reversing, auto-reversing, auto-restarting. It’s also very useful to add events that fire when the Time value updates, when the timer ends, and so on.

Download SimpleTimer.zip