Lerp Not Working As Intended

So im trying to make something move using Lerp() and I want it to take a set amount of time. The part as to move thru set waypoints (like a tower defense game enemy). The lerp is supposed to work this way:

  • Take 3 seconds to go to the waypoint;
  • once arrived to the waypoint, the part goes directly to the next waypoint.

But instead it takes one second to go to the waypoint and it stays 3 seconds on the waypoint.

Any Idea on how I could solve this?
Here is the function that lerps the part:

function Move_Enemy(enemy, enemyID)
		
	local runTime = 0
	local alpha = 0
	local lerpTime = 3
	local moveLerp
	
	local nodeAttribute = workspace.Enemies[enemyID]:GetAttribute("Node")
	local node = workspace.Path.Nodes[nodeAttribute]
	print(nodeAttribute)

	moveLerp = RunService.Heartbeat:Connect(function(deltaTime)
		task.wait()
		runTime += deltaTime
		alpha = runTime / lerpTime
			
		print(runTime)
			
		workspace.Enemies[tostring(enemyID)].CFrame = workspace.Enemies[tostring(enemyID)].CFrame:Lerp(node.CFrame, alpha)
			
		if alpha >= 1 then
			print("done")
			moveLerp:Disconnect()
		end
	end)
end
1 Like

You need to keep track of the original CFrame so that when you use :Lerp, it doesn’t use an updated CFrame. I would also just recommend using TweenService.

Code:

function Move_Enemy(enemy, enemyID)

	local runTime = 0
	local alpha = 0
	local lerpTime = 3
	local moveLerp

	local nodeAttribute = workspace.Enemies[enemyID]:GetAttribute("Node")
	local node = workspace.Path.Nodes[nodeAttribute]
	print(nodeAttribute)
	
	local originalCFrame = workspace.Enemies[tostring(enemyID)].CFrame 
	
	moveLerp = RunService.Heartbeat:Connect(function(deltaTime)
		task.wait()
		runTime += deltaTime
		alpha = runTime / lerpTime

		print(runTime)

		workspace.Enemies[tostring(enemyID)].CFrame = originalCFrame:Lerp(node.CFrame, alpha)

		if alpha >= 1 then
			print("done")
			moveLerp:Disconnect()
		end
	end)
end

TweenService method:

local TweenService = game:GetService("TweenService")

function Move_Enemy(enemy, enemyID)
	local lerpTime = 3

	local nodeAttribute = workspace.Enemies[enemyID]:GetAttribute("Node")
	local node = workspace.Path.Nodes[nodeAttribute]
	print(nodeAttribute)
		
	local movementTween = TweenService:Create(workspace.Enemies[tostring(enemyID)], TweenInfo.new(lerpTime, Enum.EasingStyle.Linear), {
		CFrame = node.CFrame
	})
	
	movementTween:Play()
	
	-- Optional: movementTween.Completed:Wait()
end
2 Likes

That should fix it. Btw I’m using lerp to make it easier to make the movement stop midway through.

Thanks!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.