Lua Utility Functions

Accurate framerate-independent lerp with delta-time:

-- `rate` is the lerp coefficient per second. So rate=0.5 halves the difference every second.
local function lerpdt(from, to, rate, dt)
	local diff = from - to           -- Target value is just an offset. Remove it and add it back.
	return diff * (1 - rate)^dt + to -- Flip rate so it's the expected direction (0 = no change).
end

Thanks to this site for the correct explanation.

Normally, the rate is the lerp coefficient per second. To adjust the time frame, divide dt by the desired time.

For example, if you want to halve a value every 1/60th of a second, do:

lerpdt(from, to, 0.5, dt/(1/60))

Has been unit tested. A basic test:

from, to, rate = 10, 0, 0.25

-- Lerp over 1 second all at once:
local result = lerpdt(from, to, rate, 1)

-- Lerp iteratively with times adding up to 1:
from = lerpdt(from, to, rate, 0.75)
from = lerpdt(from, to, rate, 0.01)
from = lerpdt(from, to, rate, 0.21)
from = lerpdt(from, to, rate, 0.01)
from = lerpdt(from, to, rate, 0.01)
from = lerpdt(from, to, rate, 0.01)
-- `from` and `result` should be equal (with some floating point error).
4 Likes