NPC lagging when turning

Hello. I made an NPC, yet it is lagging when the player turns. Here is my code:

local characters = {};
local closestCharacter = nil;
local closestCurrentMagnitude = math.huge;
local pathFindingService = game:GetService("PathfindingService");
local path = pathFindingService:CreatePath()

function child_Added(instance)
	if not instance:IsA("Model") or game:GetService("Players"):GetPlayerFromCharacter(instance) == nil then return end;
	
	if closestCharacter == nil then closestCharacter = instance end
	
	local targetIndex = #characters + 1
	
	local lastInstanceName = instance.Name;
	
	table.insert(characters, targetIndex, instance)
	
	repeat wait() until not instance.Parent
	
	table.remove(characters, targetIndex)
end;

function waypoints_Play(waypoints)
	local characterOnStart = closestCharacter
	
	for _, v in ipairs(waypoints) do
		local humanoid = script.Parent.Humanoid;

		humanoid:MoveTo(v.Position)
		
		if closestCharacter ~= characterOnStart then continue end
	end
	
	return
end;

function update_Target()
	if not closestCharacter then return end;
	
	if closestCharacter.Humanoid.Health == 0 then return end;
	
	path:ComputeAsync(script.Parent.Torso.Position, closestCharacter.HumanoidRootPart.Position)
	
	local wayPoints = path:GetWaypoints();
	
	waypoints_Play(wayPoints)
	
	closestCurrentMagnitude = (closestCharacter.HumanoidRootPart.CFrame.Position - script.Parent.Torso.CFrame.Position).Magnitude;
	
	for _, v in ipairs(characters) do
		if v ~= closestCharacter and (closestCharacter.HumanoidRootPart.CFrame.Position - script.Parent.Torso.CFrame.Position).Magnitude < closestCurrentMagnitude then
			closestCharacter = v
			
			closestCurrentMagnitude = (closestCharacter.HumanoidRootPart.CFrame.Position - script.Parent.Torso.CFrame.Position).Magnitude
		end
	end
end;

workspace.ChildAdded:Connect(child_Added)

while wait(0.3) do
	update_Target()
end

Here is the video that shows how it lags:
https://streamable.com/vehp2u
Any help?

Well, if you want a smoother turning of it, make the while wait(0.3) do into while wait(.1) do

I just did that, but it still lags.
https://streamable.com/vehp2u

Try doing NPC.PrimaryPart:SetNetworkOwner(nil), if it doesn’t have a primary part then make torso the PrimaryPart

6 Likes

Yes, this will work. It’s all about physics calculations.

I noticed he’s not using Humanoid.MoveToFinished:Wait(), not using this will make the NPC not follow paths correctly