How do you properly use the Curve resource for interpolating movement?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By pox

So, when you use a Curve and sample_baked(), you get a value whiting 0 and 1 that goes along the curve. What I don’t entirely get is how to properly use it to interpolate movement:

If you do it like this:

var x = remap(time, 0, time_to_max, 0, 1)
velocity = dir * (speed * curve.sample_baked(x))
time += delta

You get a proper interpolation of the speed, but if I start deaccelerating, I have no way to keep the velocity. So what I really want is to use it with lerp:

var x = remap(time, 0, time_to_max, 0, 1)
velocity = velocity.lerp(dir * speed, curve.sample_baked(x))
time += delta

Is this the correct way to use lerp? because without the curve you simply pass a constant acceleration and multiply it by delta. In my use case I’m passing a different value each frame, and the interpolation happens on the previous frame velocity.

Would I need to store the initial velocity and interpolate from that? If I apply the curve to a constant acceleration would that work? Maybe using move_toward() since it should take an increment rather than a percentage?

:bust_in_silhouette: Reply From: pox

Well after some testing I think this could be the proper and simpler way to handle it, just imagine dir is the input from the player:

var curve: Curve
var speed: float = 8
var time_to_max: float = 0.3

var accel = speed / time_to_max
var time = 0    

func physics_process(delta):
    var x = remap(time, 0, time_to_max, 0, 1)
    velocity = velocity.move_toward(dir * speed, curve.sample_baked(x) * accel)
    time += delta

Since move_toward() just does increments, it shouldn’t matter that you’re keeping the velocity. And then you just adjust the increment (accel) with the curve. The delta is already in the x value so no need to add it at the end, I tried and it just made it exponentially slow. You should reset the time var when not moving