CFrame :Lerp slows down parts to super slow speeds

I am trying to create a door while reusing a script I used for some of my other doors. The door works, but it slows down as it reaches it’s endpoint. This results in the debounce never changing which means it takes almost a minute to close the door after it opens.
Here’s my script:

function doorOpen()

				DOOR_OPEN:play()
				local f = script.Parent.Door1.PrimaryPart.CFrame*CFrame.Angles(0,-math.rad(90),0)
				for i = 0,1,0.0010 do
					local cfm = script.Parent.Door1.PrimaryPart.CFrame:lerp(f,i)
					script.Parent.Door1:SetPrimaryPartCFrame(cfm)

					wait()
				end

db = false
open.Value = true
end

First, void using tiny numbers in loop counters as it causes floating point errors to pile up and mess with accuracy. Opt for a loop like such:

for i = 0, 1000 do
    -- do (i / 1000) when you want to use it
end

Second, your issue is how you’re interpolating it. In your first iteration of the loop you move the door 0.1% of the way to your target, which is alright. However, since you use the primary part’s CFrame every iteration of the loop, the code uses the updated position of the door to do its new calculations. Since the distance shrunk in the last iteration, now that 0.1% has also shrunk, which makes it so every iteration after the first the loop moves the door by less and less distance to its target.

This has a simple solution: store your door’s first position outside of the loop, as such…

local door_open = script.Parent.Door1.PrimaryPart.CFrame
local door_closed = door_open * CFrame.Angles(0, -math.rad(90), 0)

for i = 0, 1000 do
    local cfm = door_open:Lerp(door_closed, i / 1000)
    script.Parent.Door1:SetPrimaryPartCFrame(cfm)
    wait()
end

Lastly, you should note wait() waits for at least 0.03 seconds, but is often more than that. If your increment is by thousands, you end up with 0.03 * 1000 in waiting period, which is about >30 seconds for your door to close.

4 Likes