Lerp and clamp

Two one-liners every game and animation ends up needing.

SNP 132 #935 Filed js gamedev

javascript
const clamp = (value, min, max) => Math.min(max, Math.max(min, value))
const lerp = (a, b, t) => a + (b - a) * t

clamp keeps a value inside a range: clamp(health, 0, 100). lerp returns the point t of the way from a to b: lerp(0, 100, 0.25) is 25.

The classic camera follow is a lerp with a small t every frame:

javascript
camera.x = lerp(camera.x, player.x, 0.1)

That's frame-rate dependent though. For the same feel at any frame rate, use the delta time:

javascript
const t = 1 - Math.exp(-speed * dt)
camera.x = lerp(camera.x, player.x, t)

The inverse, inverseLerp = (a, b, v) => (v - a) / (b - a), maps a value back to 0..1. Combine them to remap a range: lerp(outMin, outMax, inverseLerp(inMin, inMax, v)).