Using interpolators and timers
I got an email request asking for help using my interpolator and timer code I’ve been posting. Since I never really wrote up how to use them, I’m going to take a quick few minutes to walk you through the process of using these two classes. Make sure you go to the original post and download the source files. Now let’s walk the steps of playing with these classes.
1) Create a new XNA GS project and add the files to your project. Should look like this:

2) Add a ‘using’ statement for the “Utility” namespace:
using Utility;
Alternatively you can just change the namespace in all the files from the TimerInterpolator.zip file to your game project’s namespace.
3) Add these fields to your game class:
Color background = Color.CornflowerBlue; TimerCollection timers = new TimerCollection(); InterpolatorCollection interpolators = new InterpolatorCollection();
We have a Color for the window background and collections for our timers and interpolators.
4) In your Update method call Update on both collections:
protected override void Update(GameTime gameTime)
{
timers.Update(gameTime);
interpolators.Update(gameTime);
base.Update(gameTime);
}
This makes sure all the timers and interpolators do their job when you create them.
5) Change the Draw method to clear with our field. This will let us test interpolators and timers without needing more graphics:
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(background);
base.Draw(gameTime);
}
6) Now we’re ready to start playing, so I’m done numbering the steps.
First let’s do a simple example. We’ll set a timer that fires after the game has been running for three seconds that simply changes our background to pink. In your LoadContent method add this code:
protected override void LoadContent()
{
timers.Create(
3f, // how long (in seconds) before the timer ticks
false, // does the timer repeat?
timer => background = Color.Pink); // the delegate to fire when the timer ticks
}
If that last line (the ‘timer =>’ part) doesn’t make sense, give this post a read.
Give that a run and you’ll see that, sure enough, the window changes to pink after three seconds. What’s happening here? Well the TimerCollection class uses a method called Create to create timers. You set how much time passes between ticks, whether to repeat it (or just fire it once), and what to do when the timer ticks. It manages the rest inside. The method does return a Timer instance you can hang on to if you want, which is usually nice if you plan on canceling timers or stopping timers that are repeating.
Now let’s do something more interesting. We’ll still use the timer, but this time we’ll interpolate from CornflowerBlue to Pink after that three seconds. Let’s change our LoadContent method a little:
protected override void LoadContent()
{
timers.Create(
3f,
false,
timer =>
{
interpolators.Create(
0f,
1f,
i => background = Color.Lerp(Color.CornflowerBlue, Color.Pink, i.Value),
null);
});
}
Now run the game and watch as the background fades from blue to pink after waiting three seconds. See how fun this is?
The Create method on InterpolatorCollection has a few overloads which are well commented, but I’ll put them here for easy reference:
/// <summary> /// Creates a new Interpolator. /// </summary> /// <param name="start">The starting value.</param> /// <param name="end">The ending value.</param> /// <param name="step"> /// An optional callback to invoke when the Interpolator is updated. /// </param> /// <param name="completed"> /// An optional callback to invoke when the Interpolator completes. /// </param> /// <returns>The Interpolator instance.</returns> public Interpolator Create( float start, float end, Action<Interpolator> step, Action<Interpolator> completed) /// <summary> /// Creates a new Interpolator. /// </summary> /// <param name="start">The starting value.</param> /// <param name="end">The ending value.</param> /// <param name="length"> /// The length of time, in seconds, to perform the interpolation. /// </param> /// <param name="step"> /// An optional callback to invoke when the Interpolator is updated. /// </param> /// <param name="completed"> /// An optional callback to invoke when the Interpolator completes. /// </param> /// <returns>The Interpolator instance.</returns> public Interpolator Create( float start, float end, float length, Action<Interpolator> step, Action<Interpolator> completed) /// <summary> /// Creates a new Interpolator. /// </summary> /// <param name="start">The starting value.</param> /// <param name="end">The ending value.</param> /// <param name="length"> /// The length of time, in seconds, to perform the interpolation. /// </param> /// <param name="scale"> /// A delegate that handles converting the interpolator's progress to a value. /// </param> /// <param name="step"> /// An optional callback to invoke when the Interpolator is updated. /// </param> /// <param name="completed"> /// An optional callback to invoke when the Interpolator completes. /// </param> /// <returns>The Interpolator instance.</returns> public Interpolator Create( float start, float end, float length, InterpolatorScaleDelegate scale, Action<Interpolator> step, Action<Interpolator> completed)
We used the first one above which does a linear interpolation over one second. The second overload simply lets you change how long it takes so you could interpolate over five seconds or .5 seconds if you wanted. The last overload is interesting with the InterpolatorScaleDelegate. This delegate does a transformation in the Interpolator which can provide you with neat effects without needing subclasses or customizing the Interpolator class.
To understand the scale, let me explain how the Interpolator works. Under the hood, the Interpolator really has two values: “progress” and “value”. Progress is the core of the interpolator, going from 0 to 1 over the desired time. The value is then computed based on the scale delegate and the progress. By default it uses linear interpolation which doesn’t do any transformations on the progress. But you could easily substitute your own delegate that does interesting transforms on the progress to get your value. However, keep in mind what value you return. A value of ‘0′ indicates the start point of your interpolation and a value of ‘1′ indicates the end point. You can return 2 if you’d like, but know that it will be well past the end value.
The code I provided comes with a small set of delegates that you can try out. They’re all in the InterpolatorScales class, including the default linear interpolation used if no other delegate is provided.
/// <summary>
/// A static class that contains predefined scales for Interpolators.
/// </summary>
public static class InterpolatorScales
{
/// <summary>
/// A linear interpolator scale.
/// This is used by default by the Interpolator if no other scale is given.
/// </summary>
public static readonly InterpolatorScaleDelegate Linear = LinearInterpolation;
/// <summary>
/// A quadratic interpolator scale.
/// </summary>
public static readonly InterpolatorScaleDelegate Quadratic = QuadraticInterpolation;
/// <summary>
/// A cubic interpolator scale.
/// </summary>
public static readonly InterpolatorScaleDelegate Cubic = CubicInterpolation;
/// <summary>
/// A quartic interpolator scale.
/// </summary>
public static readonly InterpolatorScaleDelegate Quartic = QuarticInterpolation;
private static float LinearInterpolation(float progress)
{
return progress;
}
private static float QuadraticInterpolation(float progress)
{
return progress * progress;
}
private static float CubicInterpolation(float progress)
{
return progress * progress * progress;
}
private static float QuarticInterpolation(float progress)
{
return progress * progress * progress * progress;
}
}
Some other delegates could use Sin, Cos, or other mathematical functions. Or you can go crazy with them; I once had a delegate that combined the quadratic interpolation with a sin wave and manual offset. The key is to find some function where a progress of ‘0′ gives a value of ‘0′ and a progress of ‘1′ gives a value of ‘1′. Whatever happens in the middle is up to you.
So I hope that helps you get an idea for how to use these classes. The more you use them, the more you’ll see how nice it is to be able to fire off these objects to handle animations and pauses, rather than continually having random fields around for timing and animating things around. With that I’ll leave you with this fun LoadContent method you can toss into the test game to have some fun with your background color.
Color[] backgroundColors = new[]
{
Color.CornflowerBlue,
Color.Pink,
Color.Red,
Color.Green,
};
int currentBackground = 0;
protected override void LoadContent()
{
timers.Create(1f, true, timer => Interpolate());
}
private void Interpolate()
{
interpolators.Create(
0f,
1f,
.5f,
InterpolatorStep,
i => currentBackground = (currentBackground + 1) % backgroundColors.Length);
}
private void InterpolatorStep(Interpolator i)
{
background = Color.Lerp(
backgroundColors[currentBackground],
backgroundColors[(currentBackground + 1) % backgroundColors.Length],
i.Value);
}
Possibly Related Posts
(Automatically Generated)More Timer/Interpolator Tweaks
Interpolation: Polish's Best Friend
Borrowing From The iPhone SDK
Advancing Timing and Interpolation
Extending GamePadState

That’s so incredibly useful! I’ll have to give it a shot.
Great Articles! The Interpolator and Pool classes are very helpful.
Since I started using this, I just can’t know how I could have lived without it!!!
That’s one pretty clever use of delegates that you implemented here. So good that it should be simply part of the framework itself.
My first trial with it was to reproduce the “cliché” computer-movie-like text animation that shows a blinking underscore as a carret and draws some text, character by character.
Here is the code:
Interpolators.Timer t1 = Interpolators.Timer.Create(
0.25f,
true,
timer =>
{
if (!this.Text.EndsWith(“_”))
this.Text += “_”;
else
this.Text = this.Text.TrimEnd(new char[] { ‘_’ });
});
Interpolators.Timer.Create(
2.75f,
false,
timer =>
{
Interpolators.Timer t2 = Interpolators.Timer.Create(
0.1f,
true,
timer2 =>
{
int realLength = this.Text.TrimEnd(new char[]{‘_’}).Length;
if (realLength != TITLE.Length)
this.Text = TITLE.Substring(0, realLength + 1);
else
timer2.Stop();
});
});
Then, you just call your usual SpriteBatch.DrawString method using the Text property of the class and you’re done.
Here is a video showing the result (with a little subtility afterwards: randomly selecting characters in the string and replacing them with some others in a quick interpolated loop
)
http://blog.will2real.com/?p=188
Thank you so much Nick for this.