Is this the best way to move an enemy from waypoint to waypoint?

Hello devs!

I am currently making a Tower Defense game, and I am trying to find the optimal way of moving the enemies from one waypoint to the next.

This is what I have for that right now:

local function moveEnemy(enemy)
	if not enemy or not enemy.PrimaryPart then return end

	local speed = enemy:FindFirstChild("Speed") and enemy.Speed.Value or 10

	-- Get the original Y offset (prevents sudden up/down movement)
	local yOffset = enemy.PrimaryPart.Position.Y - enemy:GetPivot().Position.Y

	for _, waypoint in ipairs(waypoints) do
		if enemy and enemy.Parent and enemy.PrimaryPart then
			local goalCFrame = waypoint.CFrame

			-- Adjust the Y-position by keeping the enemy's relative height consistent
			local adjustedGoalCFrame = CFrame.new(goalCFrame.Position.X, goalCFrame.Position.Y + yOffset, goalCFrame.Position.Z)

			local distance = (enemy.PrimaryPart.Position - adjustedGoalCFrame.Position).Magnitude
			local duration = distance / speed
			local startCFrame = enemy:GetPivot()
			local startTime = tick()

			while tick() - startTime < duration do
				local alpha = (tick() - startTime) / duration
				local newCFrame = startCFrame:Lerp(adjustedGoalCFrame, math.clamp(alpha, 0, 1))

				-- Force Y position to prevent jitter
				newCFrame = CFrame.new(newCFrame.Position.X, adjustedGoalCFrame.Position.Y, newCFrame.Position.Z)

				enemy:PivotTo(newCFrame)
				task.wait()
			end

			-- Ensure the final position is exactly at the waypoint
			enemy:PivotTo(adjustedGoalCFrame)
		end
	end

	task.wait(1)

	-- Call base damage function instead of handling it here
	damageBase(enemy)
end

The problem right now is that some of my larger ememies are jittering as they get to the next waypoint, while my smaller enemies are moving smoothly.

Is there a way to fix this? Also, is this the optimal way of moving the enemies? I want to ensure this is not using up too much memory.

Thanks,

Sarvv

1 Like