What Is Lerp In Unity? The Right Way To Use It

Share on social media

In this article, We will discuss, what is lerp in unity and how to use lerp in unity. Lerp, which is also known as Linear interpolation is the most commonly used function in unity and it’s quite often misunderstood and can be used in the wrong way. Many developers find it a bit difficult to implement correctly. So let’s understand how to use it in the right way.

** I will also give you a bonus tip in this article, so read the complete article**

What is lerp in unity

Lerp is one of those things that we struggle to achieve the desired results especially if you are new to unity development. Even I struggled a lot in my early days. Sometimes Lerp doesn’t work at all, this might have also happened to you.

But don’t worry, today you will understand how to lerp gameobject in unity. With that said, first, let’s understand what is lerp in unity.

Lerp, also known as Linear Interpolation is a mathematical function. This is most commonly used to find a point some fraction of the way along a line between two endpoints. In simple words, It will give you point of scale between two points. 

How Does Lerp Works In Unity?

The Lerp allows us to interpolate linearly between two values. It can be specified using a minimum and maximum value (a & b) and an interpolation value (t), the interpolation value (t) returns a point on the scale between a and b.

a + (b – a) * t 

formula of linear interpolation

Lerp takes 3 arguments a,b, and t. So let’s simplify it.

 In Simple Terms, 

Let’s understand the third parameter (t) as a percentage (%), t is clamped from 0 to 1, so 0 means 0% and 1 means 100%. Now let’s take one simple example:

a = 2;
b = 6
t = 0.5;

return value = (ba) * t, which will be 2.

Let’s understand it now, so the difference between a and b is 4 and t is 0.5 (which means 50%), So 50% of the difference (which is 4) will be 2.

So if t is 0 then returned value will be a and if t is 1 then it will return b because at 0% lowest value is a and at 100% highest value is b.

I hope now you have a basic idea of how Lerp works.

How To Lerp Gameobject In Unity?

Now let’s see how to Lerp a gameobject. To understand it, Let’s say I want to move a gameobject from point (0,0,0) to B (5,0,0). So let’s see how we can achieve the same using Lerp.

So here is the code to Lerp the gameobject in unity.

using UnityEngine;

public class LerpObject : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        transform.position = Vector3.Lerp(transform.position ,
        new Vector3(5, 0, 0), Time.deltaTime);
    }
}

Above as you can see, I have used Vector.Lerp to interpolate gameobject. This is as simple it looks like we have just given a as transform.position and b as a new Vector3 which our target position, and in last we have give Time.deltatime as t which is interpolation scale or percentage.

Now let’s see how the result will look like if attach this script on the cube.

As you can see in the above video, Lerp starts at a fast pace in start and gradually slows down by the end. This is not linear then.

Why this happened because it should have been linear? Okay let me tell you, the reason is that the first argument is not fixed which is transform.position it gets updated each time, it is fast at the start because the distance is large at the start so we get a larger value in return and as the distance gets smaller we also get a smaller number in return so that is why it gets slower in the end

It can also be useful in many cases though where you want this kind of effect.

Now the question is how can we get the linear effect? To do that there is simple logic, the a and should always be static values, which means They should not be transform.position or any variable in that we are assigning Vector3.Lerp because if that will be used in a parameter then it will be updating itself and we don’t want that to achieve the linear effect. 

Let’s see how to interpolate gameobject linearly.

How To Lerp Gameobject Linearly In Unity?

Now let’s look at the correct way of using Lerp to interpolate the gameobject. For Instance, we want to move the gameobject from point A to point B with a constant speed. 

Let’s look at the code and understand how we can achieve it.

using UnityEngine;

public class LerpObject : MonoBehaviour
{
    private float desiredDuration = 3f;
    private float elapsedTime;

    // Update is called once per frame
    void Update()
    {
        elapsedTime += Time.deltaTime;
        float percentageCompleted = elapsedTime / desiredDuration;
        transform.position = Vector3.Lerp(new Vector3(0,0,0) ,
            new Vector3(5, 0, 0), percentageCompleted);
    }
}

Let’s understand the above code.

  1. First, We have defined two more variables, Called as desiredPosition and elapsedTime.
  2. We have set desiredPosition to 3 seconds because we want the cube to move from point A to B in 3 seconds, you can set it to any number you want.
  3.  The elapsed number will be increasing by Time.deltaTime for each frame in the Update method. 
  4. Then we are calculating the percentageCompleted of elapsedTime.
  5. Lastly, we have used the percentageCompleted variable in the 3rd parameter as a t.
One more thing notice here is that, Parameter a and b is constant and t is dynamic. Now let’s take a look at the result.

As you can see in the above video, the Cube is moving at a constant speed. How exactly it is working? If you are wondering the same, Let me tell you the logic behind it. What we want is to move the cube at a constant speed to make it linear. Let’s understand it with a simple calculation.

Desired Duration = 3 Seconds

We are increasing t with Time.deltaTime. So for simple calculation let’s assume we are getting 60 FPS in our game.

Time.deltaTime = 1 / 60 = 0.0167 (Time.deltaTime varies each frame, but this is for our understanding).

It means 3 seconds = 180 Frames Total Frames

Let’s check iteration by iteration.

First Iteration, elapsedTime = 0.0167, Returned value (0.0167 / 3) = 0.0056
Second Iteration, elapsedTime = 0.0334, Returned value (0.0334 / 3) = 0.0111
Third Iteration, elapsedTime = 0.0501, Returned value (0.0501 / 3) = 0.0167
Fourth Iteration, elapsedTime = 0.0668, Returned value (0.0668 / 3) = 0.0223
Fifth Iteration, elapsedTime = 0.0835, Returned value (0.0835 / 3) = 0.0278

So on and so forth till 180 times.

One Eighteenth Iteration, elapsedTime = 3 (0.0167 * 180), Returned value (3/3) = 1

Hope it is clear to you now. Now let’s see the non-linear way to interpolate gameobject.

Bonus Tip

Using Lerp With The Animation Curve

Now let’s see a different approach to using Lerp with the help of “Animation Curve”. It is easy to use in terms of handling the behavior of the interpolation. You can have better access over your interpolation journey.

Let’s look at the code that how it works exactly.

using UnityEngine;

public class LerpObject : MonoBehaviour
{
    private float desiredDuration = 3f;
    private float elapsedTime;

    public AnimationCurve animationCurve; 

    // Update is called once per frame
    void Update()
    {
        Debug.Log(Time.deltaTime);
        elapsedTime += Time.deltaTime;
        float percentageCompleted = elapsedTime / desiredDuration;
        transform.position = Vector3.Lerp(new Vector3(0,0,0) ,
            new Vector3(5, 0, 0),
            animationCurve.Evaluate(percentageCompleted));
    }
}

In the above code, We have added the AnimationCurve. It stores a collection of keyframes that can be evaluated over time. The rest is the same. 

Now let’s see how it helps us to get more control over the interpolation.  First, we will set the animation curve.

Using Lerp with AnimationCurve In Unity

According to the above curve, The Lerp will be slow at the start and will be fast after 30-40% of the journey. Let’s see the results.

Let’s try one weird curve and see how it works

Using Lerp with AnimationCurve In Unity

This would be interesting to see what the interpolation will look like. Let’s have a look at the result.

So this was it, Hope you understand how you can use it. You can play with values and curves according to your need and requirements.

Hope this article was helpful for you to understand How Lerp Works In Unity and How to lerp gameobject in unity. 

Still, some developers may find it difficult especially if they are beginners. Let’s see what common mistakes we all make while using it.

Vecto3.Lerp Is Not Working?

There can be multiple reasons because of that Lerp is not working, But here is the most common mistake developers make.

Here is one example of that:

private void Update () 
{
    transform.position = Vector3.Lerp(startPos.position,
    endPos.position, Time.deltaTime);
}

The above code will not work, the reason is that each time we will get the same value because all three parameters (a,b,t) are static they are not changing. The quick fix for this will be to replace “startPos.position” with transform.position so each frame the will be get updated.

How Do You Use Lerp In Unity?

That was from my side about Lerp, Let me know how you use Lerp, Do you use it for simple animation movements? There can be multiple ways of using it, maybe to create a smooth camera follow.

Whatever it is, Let me know by leaving a comment below. Your comment matters

I Hope someone will find it helpful. 


Share on social media

Leave a Comment

Your email address will not be published.