jthistle wrote:Hi,
I'm try to smoothly lerp between two coordinates with the formula:
Code: Select all
function lerp(a,b,t) return a * (1-t) + b * t end
However, this formula just makes the movement instant and with a constant velocity.
Does anyone know how I can get a smooth start and a smooth end, a bit like Unity's lerp function?
Thanks for any help!
lerp is an abbreviation for
linear int
erpolation. Linear interpolation always starts and stops instantly and moves, well... linearly, at constant speed.
Tjakka is right, you want some in-out easing function. There's many options of functions, but I would not say you need a library for it.
To get started: first learn quad-in interpolation. Basically you use your lerp function from above, but you take the t and preprocess it. t goes from 0 to 1, if you square it it
still goes from 0 to 1, but it starts off slower than before:
Code: Select all
function quadin(a, b, t) return lerp(a, b, t * t) end
Now your interpolation ends on a really high spsed though, so really you want to apply quad for the first half, and then apply it in reverse for the second half of t. thats how quad-in-out works:
Code: Select all
function quad_in_out(a, b, t)
if t <= 0.5 then
return quadin(a, b, t*2) - (b-a)/2 -- scale by 2/0.5
else
return quadin(a, b, (1 - t)*2) + (b-a)/2 -- reverse and offset by 0.5
end
end
This may not be the most intuitive code (and i might've made a mistake typing it from scratch here) but you should be able to figure it out.
For the first half, you multiply t by 2 to get it back onto the 0-1 scale for the first half, so the quadin function works as expected. Results are scaled in half so it stops early and the second half can continue from there.
Second half you need to reverse (1 - x) and then multiply times 2 so that at 0.5s you get a '1' and at 1s you get a '0' - you reversed and scaled the quadin function to fit the second half.
You might want to plot some of the functions involved in Wolfram alpha or something similar, that helps a lot.