You’re Using Lerp Wrong

Matt Harzewski
The Startup
Published in
5 min readJan 24, 2021

--

Linear interpolation, or “lerp” for short, is a technique commonly used when programming things like games or GUIs. In principle, a lerp function “eases” the transition between two values over time, using some simple math. This could be used to slide a character between two coordinates, or to animate a change in size or opacity of a UI element. If you lerped between two colors, you’d get a gradient. The Unity game engine includes helper functions for Lerp in the Vector, Quaternion and floating point Math classes.

The use case I’ve been working with lately is smoothing player movement from coordinate to coordinate in network code. Since there are inherent latency and bandwidth limitations over the Internet, and you can only reasonably send so many packets per second, simply updating a player’s transform from one vector to another would result in very jerky movement. The solution: for every pair of packets that come in, in which the player will only move a few meters, you lerp between the vectors over a time roughly equal to the time between the packets. This slides the character smoothly, so it doesn’t stutter around.

In my Internet travels, I’ve noticed that a lot of examples in the Unity community–that’s the game engine I’m using–are bad. (And in the words of Zoidberg, perhaps they should feel bad.)

This is the very popular antipattern I see all over the place:

public void Update() {
// [...]
pos = Vector3.Lerp(obj.transform.position, targetPosition, 0.1f);
obj.transform.position =…

--

--