Constant Speed of Lerp

I’m trying to lerp the cframe of a part to get to another distance several times. I was wondering how would I make it so no matter the distance, the lerp stays at the same constant speed.

5 Likes

It’s pretty simple, actually! Just multiply the total time to lerp by the magnitude of the distance between the start and end points :slightly_smiling_face:

(the reason this works is that speed = distance / time. If you lerp with a constant time over a set distance, speed will increase to compensate. By multiplying the time by distance you nullify this effect.)

1 Like

How would I get the total time?

1 Like

I thought this would be an already-defined parameter. What exactly is your code setup?

1 Like

for i = 0, 1, Increment do
Lets say I was lerping a part to 100 studs away and I was lerping a part to 10 studs away in a different for loop, how would I keep it so the increment is increasing in a way which both parts would travel at the same speed to get to the target.

1 Like

So your code looks something like this?

for i=0, 1, 0.1 do
    part.CFrame = startPosition:Lerp(endPosition, i)
    wait()
end

The wait() part is important to calculating the time, so just asking to make sure!

1 Like

Yes except I’m using RenderStepped:Wait(), which is 1/40th of a second, 0.025ms

1 Like

Okay! So in this case, the total time depends on how many times the for loop executes.

With everything you’ve told me in mind, here’s a solution which should work for you; I’ll explain it afterwards.

local distance = (endPosition - startPosition).Magnitude

for i=0, distance, 0.1 do
    local progress = i/distance -- since i goes from 0 to distance, we divide to get it from 0 to 1
    part.CFrame = startPosition:Lerp(endPosition, progress)
    RenderStepped:Wait()
end

Essentially what this does is makes the for loop run longer for larger distances. A really easy way of doing that is by changing the upper limit from 1 to distance, which has the effect of multiplying the time taken by the distance. To get a value between 0 and 1 to use with Lerp, we can just divide i by distance!

The above code should answer your question! Also quick correction; RenderStepped tries to run at 60fps, i.e. every 1/60th of a second :slightly_smiling_face:

7 Likes

RenderStepped is actually fired every frame, so usually it’d be 1/60th of a second.

1 Like