Question regarding this lerp function

I was wondering if there was a way to make a part move to another part within a certain time frame. I originally used the function below for this purpose. However, this function relies on speed and not a specific time. Is there a way to make this function work based on a specific time?

function Lerp(Obj: any, Goal: CFrame, Speed: number, BreakOnComplete: boolean)
	while true do
		local deltaTime = task.wait()
		local distance = (Obj.Position - Goal.Position).Magnitude
		local speed = Speed * deltaTime -- distance traveled between elapsed time
		local estimatedTime = speed / distance -- obtain a lerp fraction between distance traveled in a frame divided by the overall distance towards the goal
		local adjustedLerpAlpha = math.min(estimatedTime, 1) -- prevent the lerp from going over 1 which is over the lerp goal

		Obj.CFrame = Obj.CFrame:Lerp(Goal, adjustedLerpAlpha) -- lerps the position values at constant speed

		if BreakOnComplete == true and Obj.CFrame == Goal then
			print("Complete!")
			break
		end
	end
end

If I need to explain this better, do let me know.

Your topic belongs to #help-and-feedback:scripting-support, move it there

Can’t believe I did that. Thanks :sweat_smile:

1 Like

try sending the Speed as the distance / desired time as an argument

to get distance do (pos1 - pos2).Magnitude

maybe it will work idk

1 Like

I will try this. Thanks for the suggestion.

1 Like

I tried your idea, and it didn’t work, sorry. Thanks for your time though! I did figure it out not long ago.

Solution:

function TimedLerp(Obj: BasePart, Goal: CFrame, Duration: number)
	local FRAME_RATE = (1 / 60)
	local StartCFrame = Obj.CFrame
	local RunTime = 0
	local Alpha = 0

	while true do
		task.wait()
		RunTime = math.min(Duration, RunTime + FRAME_RATE)
		Alpha = RunTime / Duration

		Obj.CFrame = StartCFrame:Lerp(Goal, Alpha)

		if RunTime == Duration then
			print(Alpha)
			break
		end
	end
end

local Part = workspace.Part1
local Goal = Part.CFrame * CFrame.new(0, 5, 0)
TimedLerp(Part, Goal, 3)
1 Like