Pathfinding NPC lags when walking

I made a Pathfinding AI for practice, and theres one last issue

local char = script.Parent

local pfs = game:GetService('PathfindingService')
char.PrimaryPart:SetNetworkOwner(nil) 

function smartWalk(target)
	local path = pfs:CreatePath()
	
	path:ComputeAsync(char.PrimaryPart.Position, target)
	for waypoint = 1,#path:GetWaypoints(),1 do
		local j = path:GetWaypoints()
		
		if path.Status == Enum.PathStatus.Success then
			char.Humanoid:MoveTo(j[waypoint].Position)
			char.Humanoid.MoveToFinished:Wait()
		elseif path.Status == Enum.PathStatus.NoPath then
			print('no path')
			break
		end
	end
end

game:GetService('RunService').Heartbeat:Connect(function(dt)
	smartWalk(workspace.jeny.Position)
end)



As you can see the NPC follows the path, but he just stutters and turns back for a second. This is really annoying.

Can somebody help me

The reason is because you are calling a function to compute a new path each Heartbeat step, which is pretty fast, constantly creating a new path on a fast “loop” of the RunService.Heartbeat.

The idea of using the waypoints is to use events, not a Heartbeat loop. When the Humanoid reached the waypoint compute the next one, or if it fails to reach it, compute the new one, not constantly compute new ones on a “Heartbeat loop”

1 Like