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.
It’s pretty simple, actually! Just multiply the total time to lerp by the magnitude of the distance between the start and end points
(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.)
How would I get the total time?
I thought this would be an already-defined parameter. What exactly is your code setup?
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.
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!
Yes except I’m using RenderStepped:Wait(), which is 1/40th of a second, 0.025ms
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
RenderStepped is actually fired every frame, so usually it’d be 1/60th of a second.