BLOG

Notes from the KAYAC hyper-casual team

Animation Made with Interpolation Functions

Takashi Hirayama

A spring-damper that overshoots a little and settles

Quite often you end up creating motion in code.

For animation that's only watched, not interacted with, an artist will probably do a better job, but things like

  • animation that the player's input can interfere with
  • animation whose position, size, speed, number and so on change with the state of the game
  • animation that isn't worth an artist's time

tend to fall to the programmer. In this article, I, Hirayama from the Technology Department, cover the basics of making animation in code.

I should warn you that it's turned out a bit heavy on the math. Honestly, I'm bad at math, and writing this was quite a struggle. If you find a mistake, let me know and I'll fix it right away. And if anyone out there would "take the time to teach Hirayama some math", I would weep with joy, so please do.

Just have a look first

Describing motion in words is painful, so please watch it first. I've put a runnable sample on the web. It's best to read along while running it.

The buttons in the row starting with "Linear" are named after the functions; pick one and press it. Press the rewind button in the row below to play it from the starting position. The start and end positions are fixed and the motion connects them, but how it connects them depends on the function. Placing lots of keyframes to make a nice animation is the artists' job; here I'm only thinking about "connecting the gap by calculation".

The graph at the bottom right plots the scale every frame, so you can get a rough feel for the character of the motion.

If you want to look while tinkering with the code, or run it locally, the sample code is on GitHub, so please use that.

Let's look at each function in turn.

Linear interpolation (Linear button)

Linear interpolation

This connects the first value and the last value in a straight line. For an angle, for example, if it starts at 0 degrees and is 180 degrees after 2 seconds, it's 90 degrees after 1 second.

The implementation is easy. First, find where the current time lies between the time of the first value and the time of the last value.

For example, if it's 90 degrees at time 1 and 180 degrees at time 3, and the current time is 2, that's halfway between 1 and 3, so we call it 0.5. 0.5 means 50%, that is, "mix the value at time 1 and the value at time 3, 50% each".

So how do you calculate this 0.5? Like this (the corresponding code in the sample).

t = (now - t0) / (t1 - t0);

t0 is the first time (1 here), and t1 is the last time (3 here). Subtract 1 from the current time, 2. Divide that by the difference between the two times. That gives you a value from 0 to 1. Then, since this t is the blend ratio, do the blend calculation.

p = (p0 * (1f - t)) + (p1 * t);

I've called the first value p0 and the last value p1. We want p0, the first value, when t is 0, and p1, the last value, when t is 1, so multiply p0 by 1-t, multiply p1 by t, and add them.

This expression has four operators, multiply, subtract, add, multiply, which is a bit wasteful, so it's usually rearranged like this (the corresponding code in the sample).

p = ((p1 - p0) * t) + p0;

Multiply p1 minus p0 by t, which runs from 0 to 1, and add v0 to it. This is what's inside UnityEngine.Mathf.Lerp. If you set a=(p1-p0) and b=p0, you can see it's the linear function p=at+b.

So how does this one move? It's straightforward, I suppose, but there's nothing interesting about it. Unless the motion is over within 0.2 seconds, I rarely use this. It feels a bit lazy. Living things, at least, rarely move like this.

Quadratic interpolation, zero initial velocity (QuadraticBeginV0 button)

So what shapes can we think of besides linear interpolation? "Linear" means a "first-degree function" like p=at+b, so next let's try a quadratic function, p=at^2+bt+c.

There are three values that determine the shape of the expression: a, b and c. The first and last values give us two equations, but with three unknowns, we're one equation short. We'll have to add another equation and solve them as simultaneous equations.

Simultaneous equations

Some of you may be thinking "how many years has it been since I heard the words 'simultaneous equations'?", so let's solve simultaneous equations using the linear function from before as an example.

Let the function be p=at+b. We want to know a and b, so there are two unknowns. From the conditions at the first time, 0, and the last time, 1, we get two equations:

p0 = a*0 + b
p1 = a*1 + b

The first immediately gives b=p0, and substituting that into the second gives a=p1-p0. In other words, we get p=(p1-p0)t+p0.

Now let's do the quadratic the same way. First, two equations are determined by the first and last values.

p0 = a*0*0 + b*0 + c
p1 = a*1*1 + b*1 + c

We're one equation short, so we add a condition; here, let's try "the velocity at the start (initial velocity) is 0".

Velocity is the derivative of the function. Differentiating p=at^2+bt+c gives p'=2at+b. This is 0 at time 0, so

0 = 2*a*0 + b

and we have our three equations. Removing the 0s and 1s and lining them up:

p0 = c
p1 = a + b + c
0 = b

b and c are already solved, aren't they? Substituting the 1st and 3rd into the 2nd gives a:

a = p1 - p0
b = 0
c = p0

The function is p=(p1-p0)t^2+p0. The code to calculate it is

float a = p1 - p0;
return (a * t * t) + p0;

(the corresponding code in the sample).

Motion

So how does this one move? It's QuadraticBeginV0 in the sample.

Quadratic interpolation with zero initial velocity

The gradual acceleration from zero speed feels good, but the abrupt stop feels a little unnatural. In the real world, things stop suddenly when they collide, and then they overshoot slightly, deform or bounce back. Maybe that's what's missing, and why it feels a bit flat. Perhaps it would work if there were a "sense of impact" from an effect or sound when it finishes.

A note on the expression

The function we got is p=(p1-p0)t^2+p0, but if you write t^2 as s, it becomes p=(p1-p0)s+p0, the same shape as a linear function. That means you get the same result by squaring t and then feeding it into the linear function. If you've written it with linear interpolation and then think "I'd like some acceleration", just one line,

t *= t;

makes it quadratic and gives you a sense of acceleration.

Quadratic interpolation, zero final velocity (QuadraticEndV0 button)

If the initial velocity can be zero, so can the final velocity.

Quadratic interpolation with zero final velocity

It starts moving sharply, so it seems good for things like the response to pressing a button.

That reminds me: I read somewhere that "if the gap between cause and effect is 0.14 seconds or more, people can no longer feel the causal relationship". I don't know if it's true, but ever since I heard it, I've made a point of building things so that pressing something produces a big enough response within 0.14 seconds. For example, I make popups spread out enough within 0.14 seconds (pressing the "popup motion" toggle in the sample changes the animation to a popup style).

Deriving it

Let's determine the shape of the function.

Getting two equations from the values at the two times is the same as before, and so is making one equation from a condition on the velocity, that is, the derivative. But the velocity condition is now about "time 1".

0 = 2*a*1 + b

Rearranging a little gives b=-2a, which is more of a hassle to solve than b=0. Solving it:

a = p0 - p1
b = -2 * (p0 - p1)
c = p0

Written straightforwardly, the code to calculate it is

var a = p0 - p1;
var b = -2f * a;
return (a * t * t) + (b * t) + p0;

but written like this it has lots of multiplications, so it's slow and the error is large too, with nothing going for it. Factor out t from p=at^2+bt+c as much as possible to get p=(at+b)t+c, and turn that into code.

var a = p0 - p1;
var b = -2f * a;
var ret = a;
ret *= t;
ret += b;
ret *= t;
ret += p0;
return ret;

Compute at, add b, multiply that by t, and add c (the corresponding code in the sample). I used one line per operation to make it easy to read, but you could just as well join it up as return (((a*t) + b) * t) + p0;. This way of evaluating a polynomial is called Horner's method.

Cubic interpolation, zero initial and final velocity (CubicBoundaryV0 button)

With a quadratic, you can specify only one of the initial and final velocities. There are three unknowns, so you can only set up three equations. If you want the velocity to be zero at both the start and the end, you need a more complex function with more unknowns. So let's try a cubic.

Deriving it

Let the function be p=at^3+bt^2+ct+d. First, the values at times 0 and 1 are p0 and p1, which gives two equations.

p0 = a*0*0*0 + b*0*0 + c*0 + d = d
p1 = a*1*1*1 + b*1*1 + c*1 + d = a + b + c + d

That gives us d right away. Next, set up two equations from the velocity conditions. The derivative is p'=3at^2+2bt+c, so

0 = 3a*0*0 + 2b*0 + c = c
0 = 3a*1*1 + 2b*1 + c = 3a + 2b + c

c is solved too. We're down to two unknowns, so let's tidy up the equations.

p1 = a + b + p0
0 = 3a + 2b

It's probably easiest to rewrite the first as b=... and substitute it into the second. Solving it:

a = 2(p0-p1)
b = 3(p1-p0)
c = 0
d = p0

and the code to calculate it, with Horner's method, is

float a = 2f * (p0 - p1);
float b = 3f * (p1 - p0);
var ret = a;
ret *= t;
ret += b;
ret *= t;
// c=0, so add nothing
ret *= t;
ret += p0;
return ret;

(the corresponding code in the sample).

Motion

The motion looks like this.

Cubic interpolation with zero velocity at both ends

It accelerates from the start and decelerates to the end. It looks handy when you want smoothness.

I want interpolation that plays well with player input

We've looked at four now, and the four have something in common: "once the time is fixed, the value is fixed exactly". Since the only variable needed is the time, they're easy to handle, but this can actually cause trouble.

The "I want to close the popup while it's still opening" problem

Say pressing a button makes a popup appear while scaling up. Any function shape will do, but "a quadratic with zero final velocity" is probably a good choice. Now, suppose the button is pressed again before the popup has fully scaled up. That probably means "cancel". You close the popup.

You could just make it vanish instantly, but if you also want an animation when it closes, it gets a bit fiddly.

The easy way is to close it by running the same function backwards, but I think the response to input should be sharp. A quadratic with zero final velocity decelerates, and run backwards it accelerates, so the response would be sluggish.

So you want to "have separate functions for opening and closing". You'd prepare "a quadratic with zero final velocity" for both opening and closing, but opening goes "from scale 0 to 1" and closing goes "from scale 1 to 0", so the values differ, which makes them different functions.

Then, if the close button is pressed at, say, t=0.8, you calculate the corresponding t for the closing function and start the animation from there.

Let me explain with a concrete example.

For opening, prepare a quadratic with zero final velocity that's at scale 0 at t=0 and scale 1 at t=1. The function is p=-t^2+2t. For closing, prepare a quadratic with zero final velocity that's at scale 1 at t=0 and scale 0 at t=1. The function is p=1-t^2.

Say we press the button and the popup comes out. The animation progresses, and at t=0.5 we press the button again and close it from there. At t=0.5, p=-(0.5*0.5)+(2*0.5)=0.75. It's at 75% scale. We fit this to the closing expression, p=1-t^2.

Since p=1-t^2=0.75, solving for t gives t=sqrt(0.25), which has two solutions, t=0.5 and t=-0.5. In this case we can ignore the negative solution, so take the positive one. We play the closing animation from t=0.5.

This was still manageable because the functions are simple, but if they get a little more complex, this work becomes horribly tedious. Think about what happens if both are cubic. With the function p=at^3+bt^2+ct+d, say p is now 0.8. What's the corresponding t? That's a problem of solving a cubic equation, which is quite a hassle, and on top of that there isn't necessarily only one answer.

So when "something cuts in partway and you want to switch to another function", you want an easier method.

Expressing it as a step-by-step calculation

If you assume something will cut in partway, the simple approach is to hold "the current value" and move it by applying a correction to it every frame.

In the popup example, start at scale 0 and add 0.1 every frame, and it reaches 1 in 10 frames. If it's pressed again partway, subtract 0.1 every frame instead, and it'll reach 0 eventually. No tedious calculation required.

p += 0.1 * Time.deltaTime;

In practice, as above, you multiply 0.1 by Time.deltaTime before adding it. Otherwise it moves faster on machines with higher frame rates.

It's really simple, but unfortunately this is the same motion as linear interpolation, and it doesn't have many uses. Is there some other nice calculation?

Exponential function (Exponential button)

Besides adding a fixed amount every frame, what other calculations are there for approaching a target value?

There are probably many, but where there's addition, there's surely multiplication too. How about a calculation like "the difference from the target value becomes 0.9 times every frame"?

p += (p1 - p) * 0.1f;

p1 is the target value and p is the current position. (p1-p) is the difference from the target. Add 0.1 times that to p, and the distance to the target becomes 90%. What was 500 km to go becomes 450 km. Calculate again the next frame and it advances 45 km, 0.1 times 450 km, leaving 405 km. That's how it keeps getting closer.

When you actually use it, as before, use Time.deltaTime so it doesn't depend on the frame rate.

p += (p1 - p) * 0.1f * Time.deltaTime;

If you multiply by deltaTime, leaving it at 0.1 is far too slow, so you'll end up making it bigger.

Motion

Let's look at this motion. Choose Exponential in the sample.

Exponential interpolation

It's similar to the quadratic with zero final velocity, but the ending is more gradual. Also, since it's a step-by-step calculation, if you press the switchGoal button partway to change the destination, it responds immediately and continues from there.

But the ending does feel too gradual. In fact, this function never reaches its destination. Recall the calculation from earlier. In the example approaching from 500 km, after 10 calculations there are still 174 km left. After 40 calculations it gets within 7.4 km, but it never gets to zero. If you wait a while it looks like it stops, but it "only looks stopped because it's so slow"; it's actually still moving.

And you can't easily specify how long it takes, either. Near the top center of the screen it says ExpCoeff, and you can adjust it with the slider to its right. This is used in place of the 0.1 in the expression earlier. At 1, it gets to about 63% (1-1/e, where e is the base of the natural logarithm) after roughly 1 second. At 2, it gets to about 86% (1-1/e^2) after roughly 1 second. You can do things like "calculate the parameter that takes t seconds to reach 99%", but whether 90% or 99% is right depends on the use and on taste, so it's quite a nuisance. I often just put in 4 and see how it looks, but there's no basis for that. With a quadratic or cubic, you reach the final value when t=1, so this is much more awkward by comparison.

The theory

Now, this is actually an exponential function, but what does that mean? If you're not interested in the theory, feel free to skip this.

Exponential interpolation

First, let's think about simply interpolating with an exponential function.

To interpolate between two points with an exponential function, a function of the form p=a*exp(-k*t)+b is handy. It's like replacing the t of the linear function with exp(-k*t). The inside of exp is made negative, so exp is 1 at t=0 and exp is 0 as t goes to infinity.

p0 = a*1 + b
p1 = a*0 + b

From these, b=p1 and a=p0-p1. So the function is p=(p0-p1)*exp(-k*t)+p1. k is a value you can choose freely. You can use it to tune the motion.

Now, the process I wrote earlier was

p += (p1 - p) * 0.1f * Time.deltaTime;

The claim is that the result of repeating this every frame has the same shape as the function p=(p0-p1)*exp(-k*t)+p1.

Integration

Building up a value by adding something again and again is, in the end, integration.

Think about the example of adding 0.1 at a time. The function you get by adding 0.1 at a time was the same as the linear function p=at+b. In other words, integrating 0.1 gives a linear function. Put the other way around, differentiating a linear function gives a constant, which is right: p'=a. That a was 0.1.

So if you want to turn some function into a step-by-step calculation, differentiate it and add that every frame. Differentiate and then integrate and you get back where you started, right?

Differentiating the exponential function

So let's differentiate the exponential function. First, the derivative of exp is exp, but if the t inside is multiplied by something, you bring that outside and multiply. exp(-k*t) becomes -k*exp(-k*t). As a result,

-k*(p0-p1)*exp(-k*t)

is the derivative. Then we pin down the variables' values to suit our use here. If we decide that we're always "starting the interpolation now", p0 can be replaced by the current position p, and t is always 0. The inside of exp becomes 0, so exp becomes 1 and disappears. While we're at it, move the leading minus inside (p-p1) to flip the subtraction, and integrate with the simplest method, Euler's method, and we get

p += (p1 - p) * k * Time.deltaTime;

With Euler's method, you multiply the derivative by Time.deltaTime and add it to the current value. Put 0.1 in k and it's the same as the original expression.

Caveats

Used as is, it occasionally does dangerous things. Imagine k * Time.deltaTime becoming greater than 1. It goes past the target value. And beyond 2, catastrophic things happen.

Say we're now "100 km from the target". If k * Time.deltaTime is 3, the next frame's calculation produces the terrifying state of "shooting far past the target out the other side, with the distance growing to 200 km". The frame after that, the distance grows to 400 km, and it keeps getting farther away. Eventually it exceeds the limit of float and reaches infinity, and in Unity's case, if you put that into a Transform or into vertex positions, Unity itself crashes (only the Mac editor?). So when you use this expression, you need to put a limit on the value of k, and it's probably also a good idea to set Maximum Allowed Timestep in Unity's settings to a value that isn't too big. How about 0.1 or so?

But where did this problem come from? Did we make some weird approximation?

Actually, the problem is the part that said "integrate with Euler's method". If you integrate properly, you have to find the definite integral from t=0 to t=Time.deltaTime (dt from here on, since it's long) and add that. Fortunately, in this case that's easy, so let's do it. We know the function after integration, so it's simple. Putting t=dt into the indefinite integral (p-p1)*exp(-k*t) gives (p-p1)*exp(-k*dt), and putting in t=0 gives (p-p1), so

(p - p1) * (exp(-k * dt) - 1)

is the definite integral. Matching the direction of (p-p1) to the earlier expression and writing it as code:

p += (p1 - p) * (1f - Mathf.Exp(-k * Time.deltaTime));

If you don't want unnecessary worries, implementing it this way is the safer choice, isn't it?

Uses

Exponential interpolation is very handy, and I use it for almost anything that player input might interrupt. Instead of the time, you remember the current value, and simply by swapping the target value and the parameter (the coefficient above), it interpolates on its own. The current value is in the RectTransform anyway, so if taking the value from there isn't a hassle, you don't even need to keep the current value yourself. Even if you swap the target value like crazy with button presses and so on, it interpolates reasonably.

The drawbacks, though, are that deciding on the parameter is a nuisance, and that its endless creeping along feels unpleasant. For example, with a parameter of 1 it takes more than 4 seconds to reach the 99% position. Yet it passes 50% in under a second, so the ending is a little too slow. If you don't like that, you may be better off using a quadratic, even if it's a bit more hassle.

By the way, there are many phenomena in nature that approach a target value endlessly in an exp-like way. The way hot water cools is exp. And how much an object fades from view on a foggy day is determined by an exp with the distance as the variable. Phenomena of the type "every time the variable goes up by 1, it falls to N%" are exp. Even where player input doesn't cut in, I think there are plenty of situations where it's useful.

Spring-damper (SpringDamper button)

There's one more interesting one, so let me introduce it. It's a method based on physics simulation.

Imagine an object at p tied by a spring to a stake driven into the ground at p1. This spring is naturally very short, and it's been forcibly stretched to tie them together. When you let go, the object at p is pulled toward p1. Eventually the spring shrinks back to its natural length and it stops there. p should end up roughly near p1.

We'll make use of this.

Physics simulation may sound hard, but it isn't. First, prepare a way to calculate acceleration. In this example, if the spring is stretched, apply acceleration in the direction it contracts. Then every frame, integrate (that is, add up) the acceleration to calculate the velocity, and integrate (add up) the velocity to calculate the position.

a = CalcAccel(); // calculate the acceleration (a as in accel)
v += a * dt; // v as in velocity
p += v * dt; // p as in position

As always, we multiply by dt (=Time.deltaTime) before adding so that we get similar results regardless of the frame rate.

As for calculating the acceleration, the rule is "the farther from the target value, the harder it pulls", so how about something like this?

a = (p1 - p) * spring; // p1 is the target value

The bigger p1-p, the bigger a. spring is a tuning parameter you can set however you like.

Let's just see how it moves

Here's the motion you get.

Spring without damping, oscillating forever

It doesn't stop.

Come to think of it, a spring stops in the real world because there's friction. Without friction, it overshoots, comes back to the same place, and oscillates forever. In fact, if you define the acceleration with the expression above and integrate it, the position becomes a sin function. It's sin, so naturally it oscillates forever.

So let's put in something equivalent to friction. Look at the motion first.

Spring-damper settling down

The motion has settled down. The difference from before is that the slider labeled damper at the top right of the screen is no longer 0. A damper is "something that attenuates", and a system controlled by this mechanism is sometimes called a mass-spring-damper system.

If you weaken the damper value, you can also get the behavior of "overshooting a little, coming back and settling".

Spring-damper overshooting a little and settling

Things in the real world can't stop instantly; they either decelerate with room to spare or overshoot and come back a little, and this is the same. Make the damper stronger and it decelerates with room to spare; make it weaker and it overshoots and comes back.

Code

The function that does the calculation looks like this (the corresponding code in the sample).

float a = ((p1 - p) * spring) - (v * damper);
v += a * dt;
p += v * dt;

a is the acceleration: it accelerates by adding the difference between the target and current values multiplied by spring, and decelerates by subtracting the velocity multiplied by damper.

Characteristics

What's distinctive about this spring-damper approach is that the start is smoother than with the exponential function. With the exponential function, the moment you switch the target value is the moment of maximum speed, but here it takes a little time to accelerate. And being able to oscillate is another feature the others don't have.

To be honest, it's not as easy to use as the exponential function. There are two parameters, which makes tuning a nuisance, and it's even harder than with exponential interpolation to predict how long it'll take to settle. With exponential interpolation you could say something like "63% after 1 second", but here it's hard to tell "which parameter values give what".

But it suits cases where you want oscillation, and there are uses where a sluggish response is better. Moreover, if you change the target value every frame, it doesn't matter much that the time to settle is hard to calculate. These characteristics suit, for example, camera control. You need to change the target value one after another to follow in-game input, a sluggish response is more realistic, and the oscillation of overshooting a little and coming back adds to the realism too.

One more thing: with this approach it's easy to mix in sudden movements partway. Say character B is chasing character A, and someone hits B with a ball and knocks it flying. If you choose SpringDamper in the sample program, a button called pulse appears in the bottom row. Pressing it knocks the object flying by adding a value directly to the velocity.

Knocked flying by a pulse, then heading back to the target

However and whenever it's disturbed, it heads for the target value while moving in a reasonably plausible way. This is only possible because it has a velocity.

Caveats

With the exponential function, I told the story of "integrating with Euler's method made it fly off to the edge of the universe and killed Unity". The same thing happens here. Look at the code again.

float a = ((p1 - p) * spring) - (v * damper);
v += a * dt;
p += v * dt;

If spring, damper, or dt gets large, it flies off to the edge of the universe.

Tuning range for damper

Let's think about damper first. Set spring to 0. Then

v += -v * damper * dt;
p += v * dt;

If damper * dt is greater than 1, the velocity reverses. It's the same as overtaking the target value with the exponential function. Beyond 2, the velocity keeps growing and eventually kills Unity.

So damper needs a limit. Restrict its tuning range so that damper * dt doesn't exceed 1. In other words,

maxDamper = (1f / Time.maximumDeltaTime);

Tuning range for spring

Next, let's think about the tuning range for spring. Set damper to 0.

v += (p1 - p) * spring * dt;
p += v * dt;

As it stands this isn't very clear, so to work out "so what happens to the position?", replace the v in the second line with the calculation from the first line.

p += (v * dt) + ((p1 - p) * spring * dt * dt);

We don't know what v is doing, but at any rate, if spring * dt * dt exceeds 1, it looks like p would overtake p1. spring * dt * dt < 1 means, in other words, that the safe choice is

var maxDt = Time.maximumDeltaTime;
maxSpring = (1f / (maxDt * maxDt));

If Time.deltaTime is at most 0.1, the maximum for spring is 100. Shove in anything more and it may overshoot or fly off to the edge of the universe.

It should also be possible, as with the exponential function, to calculate the definite integral properly instead of approximating with Euler's method. Wikipedia and this document should help. But it's a real hassle, so I haven't done it.

Below are a button and a popup that I made with this as a test. Since they're spring-dampers, they can show the behavior of overshooting slightly and coming back, and it's easy to switch to a different motion partway. Tuning them takes some getting used to, though.

A button and a popup animated with a spring-damper

There are other functions too

We've looked at quite a few, but there are many other functions you can use for interpolation. Just off the top of my head, there are

  • polynomials of degree 4 or higher
  • trigonometric functions
  • reciprocals
  • square roots and cube roots
  • logarithms

and so on. If the conditions are met, I think interpolating with these is fine too. Personally, though, I can't think of many uses. About the only one is that I sometimes use trigonometric functions when I simply want something to oscillate, but I feel a spring-damper would do the job. You can knock it around partway, too.

Closing

The whiff of math got a bit strong, but "motion" = "change in a number" = "function", so it can't be helped (I'm bad at math, so writing it was a struggle).

But this topic is the foundation for subjects like

  • camera control
  • interpolating 3D rotations (using quaternions)
  • controlling the movement of AI-driven characters

and it's a deep field that has quite a lot to do with how a game feels to play. I plan to keep honing my skills so that I can deliver results in those areas.