Lerping with PivotTo moves ant model 4 gazillion studs away

I’m doing some basic Linear Interpolation between 2 points.|

Summary of the purpose of this code.

The purpose of my script is to manage a number of ants (models) that will move to random positions around the player. To reduce as much remote events as possible from being fired to the server I have made it so over half of the ants have to have made it to a new position in order for them all to move again. Before I implemented this an event was fired to the server immediately after an ant reached the newPosition.

My issue

After “alpha0” reaches 1, the ant seems to move a very far distance away. Both children of the ant are very far away however the position of the origin and WorldRoot of the ant model seems to be normal and lerps as normal once over half of ants have made it to a new location.

Main movement function where the problem lies

local function PerformMovement(ant: Model, hrp: Model, newPosition: Vector3, speed: IntValue, beeCount: number)
	local StartPosition: Vector3 = ant.WorldPivot.Position
	local difference: Vector3 = (StartPosition - newPosition)
	local distance: IntValue = difference.Magnitude
	local MoveConnection: RBXScriptConnection; local alpha0: IntValue = 0

	local BeeQueue = coroutine.wrap(function()
		table.insert(Ant_Module.Queue, {ant, newPosition}) -- at this point new position should be the current position of the ant
		
		if #Ant_Module.Queue >= (math.round(beeCount / 2)) then
			REPLICATED_STORAGE.AntGoalReached:FireServer(Ant_Module.Queue)
			table.clear(Ant_Module.Queue)
			coroutine.yield()
		end
	end)

	MoveConnection = RUN_SERVICE.RenderStepped:Connect(function(delta)
		if not ant then MoveConnection:Disconnect() return end -- mightve been destroyed

		alpha0 = math.clamp(alpha0 + (speed * delta) / distance, 0, 1)

		local Interpolation: Vector3 = StartPosition:Lerp(newPosition, alpha0)
		ant:PivotTo(CFrame.new(Interpolation, newPosition))

		if alpha0 >= 1 then
     -- print statements have shown this if statement still runs even though the ant is 3 gazillion studs away.
			MoveConnection:Disconnect()
			BeeQueue()
		end
	end)
end

If you have any idea what might be causing this werid phenomenon let me know.

1 Like

Hard to tell with this piece of code. Try watching or printing your variables to see where it is (potentially) miscalculating.

1 Like

alpha0 calculation is normal, this started happening after i implemented by coroutine that halves the beecount so perhaps it’s something to do with that

1 Like