Creating Smooth Transitions Using Linear Interpolation
In this lesson, you will learn how to create fluid, frame-rate independent transitions between two values by combining Mathf.Lerp with Time.deltaTime.
The Problem with Simple Lerp
If you have used Mathf.Lerp(current, target, 0.1f) inside Update(), you might have noticed that the movement speed changes if your game's frame rate fluctuates. This happens because Update() runs once per frame; on a computer running at 144 FPS, that "0.1" is applied many more times per second than on a computer running at 30 FPS.
The Solution: Time-Based Interpolation
To fix this, we replace the fixed percentage (like 0.1f) with a value that considers how much time has passed since the last frame. By multiplying our interpolation speed by Time.deltaTime, we ensure that the transition covers the same distance regardless of how many frames the game renders.
Here is how you implement this to move an object smoothly toward a target:
public Transform target;
public float speed = 5.0f;
void Update()
{
// We calculate a 't' value that is frame-rate independent
float step = speed * Time.deltaTime;
// Lerp from current position to target position
transform.position = Vector3.Lerp(transform.position, target.position, step);
}
How it Works
Vector3.Lerp: This function calculates a point between two positions. The third parameter,t, represents the percentage (0 to 1) of the distance to travel.speed * Time.deltaTime: By multiplying your desired speed by the time elapsed since the last frame, you create a "smoothing factor." As the object gets closer to the target, the remaining distance decreases, which naturally causes the object to slow down as it arrives, creating a professional "ease-in" effect.
Remember: Mathf.Lerp (or its vector equivalents) does not know how fast it should go on its own; it is your responsibility to provide the time-scaled increment to keep the transition smooth across all hardware.
Key Takeaway: Always multiply your interpolation factor by Time.deltaTime to ensure your transitions feel identical regardless of the user's frame rate.