unity interpolation

Lerp() is a common source of confusion for newbies. Many (bad) “tutorials” use it in a careless way and don’t explain its actual function. It’s one of a few things I can claim to fully understand, so here we go.

Let’s just get this out of the way: all Mathf.Lerp() does is return a position half-way between two variables. In game development if you want to move something from a beginning point to an end point what you’re really talking about is applying linear interpolation to find a range of points that can be used for animation.

Interpolation takes a lot more than just a Lerp() method call. Here are the variables I’ll use to interpolate a variable over time:

-A reference to a variable that will animate.

-The value it starts moving from.
-The value it ends at.

-An amount of time it takes to reach the end.
-The amount of time that has passed.
-The position of the interpolation at a given percentage of that time passed..

Here is an academic example. In practice the startPosition would often be copied from a supplied movingFloat at the beginning of such a method.

IEnumerator Interpolation()
    float startPosition = 0;
    float endPosition = 100;

    float movingFloat = 0;
    float currentPosition = 0;
    float percentComplete = 0;
    float totalDuration = 5; // 5 seconds

    for (float timePassed = 0;  timePassed < totalDuration; timePassed += Time.deltaTime)
         percentComplete = timePassed / totalDuration;

         // percentComplete = percentComplete * percentComplete; // exponential curve

         currentPosition = Mathf.Lerp(startPosition, endPosition, percentComplete);
         movingFloat = currentPosition;

        yield return 0;

Here’s a great article that helped me understand how to correctly write these methods.

I recommend beginners initially write their own interpolation methods. Creating methods like these myself was good practice; and led me to learn more advanced C# concepts as I searched for ways to make them more portable and generic. Ultimately, plugins like DOTween allow us interpolate anything with a choice of curve using one method call.

Challenge: Can you make the interpolation more accurate? (Hint: use a while() loop and one if() statement.)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s