- Home /
smooth function with overshooting
I need a smooth function that can accelerate at start, decelerate near the target, but can also overshoot a bit then return back to target until it will reach it. I tried SmoothDamp but it's too precise. How can I do this?
Answer by Bunny83 · Oct 25, 2020 at 04:06 PM
Well you just want to pick an easing function that works on the usual 0 to 1 range and outputs an "eased" value. A good reference source is this page. You probably looking for the easeInOutBack which does perform an overshoot at the start and the end.
Note that you can not really use a method like SmoothDamp in such a case. So no method that updates the position based on the current / last position. This would be way too complex to disect as this involved the second derivative of your whole method in order to figure out the required speed change over time. So you have to use a proper lerp. Since you want overshoot you have to use Mathf.LerpUnclamped otherwise you can not get any overshoot. Just like the normal lerp you have to keep your start and target values fix and just use a t value that goes from 0 to 1 and put it through your desired easing function.
This is the "EaseInOutBack" function written in C#
public static float EaseInOutBack(float t)
{
const float c1 = 1.70158f;
const float c2 = c1 * 1.525f;
float t2 = t-1f;
return t < 0.5
? t * t * 2 * ((c2 + 1) * t * 2 - c2)
: t2*t2 * 2 * ((c2 + 1) * t2 * 2 + c2) + 1;
}
and you would use it like this:
float v = Mathf.LerpUnclamped(fromV, toV, EaseInOutBack(t));
for a float value v that should go from "fromV" ro "toV" as "t" goes from 0 to 1.
It works the same way with Vectors:
Vector3 v = Vector3.LerpUnclamped(fromV, toV, EaseInOutBack(t));
Of course here "fromV" and "toV" are your start and end vectors.
Answer by Zubzuke · Oct 26, 2020 at 12:27 AM
Nevermind, I've found a very natural and inexpensive solution. I'm using a speed and an acceleration to build up velocity and when current is close enough to target then the acceleration is reversed to begin braking. An initial distance is computed every time a new target is set. Acceleration is also reversed if current has passed target by. And by tweaking the braking distance I can get as many oscillations around the target as needed. Anyway, thanks for your help!