Linear Interpolation

Wed 15/01/2020

What is Linear Interpolation?

Pick up a pencil or a pen. Choose two points on a blank piece of paper and draw a straight line between them. Congratulations! What you've just done is Linear Interpolation.

Unity Lerp - Er,... What?

Unity has its own linear interpolation system that you can use to move your gameObjects around. You need a start position, an end position and a float between 0 and 1 representing where along the line you are. Think of it as a percentage. If you are at 0%, you are at the start point, 100% would be the end point and 50% (or 0.5) would represent half way between those points.

Vector3.Lerp(Vector3 startPos, Vector3 endPos, float t)

But how are you supposed to use it?

Unity Coroutines, of course!

The [SerializeField] attribute allows you to change the values in the Unity Editor. Since they are private in the C# script here, you cannot access them in code from other scripts.

using UnityEngine;
using System.Collections;

public class LerpClass {

    [SerializeField] private float animationTime;
    [SerializeField] private Vector3 startPos;
    [SerializeField] private Vector3 endPos;
    
    public void MoveObject() {
        StartCoroutine(nameof(MoveObjectUsingLerp));
    }
    
    private IEnumerator MoveObjectUsingLerp() {
        // The normalised time which will go between 0 and 1
        float normalisedTime = 0f;
        
        // The time in seconds
        float t = 0f;
        
        while (t < animationTime) {
            // Normalise the time
            normalisedTime = t / animationTime;
            
            // Move the gameObject, which has this script attached, from the 
            // start possition to the end position
            transform.position = Vector3.Lerp(startPos, endPos, normalisedTime);
            
            // Increment the time by Unity's delta time.
            t += Time.deltaTime;
            
            // Wait until the end of the frame.
            yield return null;
        }
        // The normalised t value will never reach 1 so move the gameObject, 
        // which has this script attached, to the end position.  
        transform.position = endPos;
    }
}

You can read more about Vector3.Lerp here: https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html

Last updated

Was this helpful?