How to make a better pathfinding?

Hello, im currently making a pathfinding system for my npc, im pretty new to pathfinding since i never got the oportunity to use it until now so i dont know much about it; i made the script inside my model so i can test things out more easly but ill make a handler later on since i want to add more types of npcs later.

Anyways, what im doing right now is i make a new thread which constantly looks for a target every 3 seconds, then on the main thread i make a while loop which makes a new path and then waits with RunService:Heartbeat:Wait().
My problem is that the npc never gets to reach the player since it makes a path but its never fast enought to reach the player, here is a video:

Here is the loop that finds a target:

task.spawn(function()
	while true do
		local nearestDistance = nil
		
		for _, player in Players:GetPlayers() do
			local character = player.Character
			local distance = (character.HumanoidRootPart.Position - modelRootPart.Position).Magnitude
			
			if not character or distance > maxDistance or (nearestDistance and distance >= nearestDistance) then
				continue
			end
			
			nearestDistance = math.round(distance)
			currentTarget = character
		end
		
		if currentTarget ~= nil and (currentTarget.HumanoidRootPart.Position - modelRootPart.Position).Magnitude > maxDistance then
			currentTarget = nil
		end
		
		task.wait(3)
	end
end)

Here is the main thread:

while true do
	if currentTarget ~= nil then
		local humanoid = currentTarget:FindFirstChild("Humanoid")
		local humanoidRootPart = currentTarget:FindFirstChild("HumanoidRootPart")

		if humanoid and humanoidRootPart then
			local success, errorMsg = pcall(function()
				local computedPath = path:ComputeAsync(modelRootPart.Position, humanoidRootPart.Position)
			end)

			if success and path.Status == Enum.PathStatus.Success then
				for _, waypoint in path:GetWaypoints() do
					if waypoint.Action == Enum.PathWaypointAction.Jump then
						modelHumanoid.Jump = true
					end

					local waypointBaseClone = wayPointBase:Clone()
					waypointBaseClone.Position = waypoint.Position
					waypointBaseClone.Parent = workspace
					Debris:AddItem(waypointBaseClone, 1.5)

					modelHumanoid:MoveTo(waypoint.Position)
					modelHumanoid.MoveToFinished:Wait()
				end
			else
				warn("Its not possible compute a path for the current target!")
			end
		end
	end
	RunService.Heartbeat:Wait()
end

I also set the network owner of the parts and have an AgentRadius of 4 so there shouldnt be any problems with that.

local path = PathfindingService:CreatePath({
	AgentRadius = 4,
	AgentCanClimb = false,
	AgentCanJump = true,
})


for _, part in model:GetChildren() do
	if part:IsA("BasePart") then
		part:SetNetworkOwner(nil)
	end
end

How can i make it so it actually follows the player without replacing the loop with RunService.Heartbeat:Connect(function()?
Is there any way to optimize more this pathfinding system? I want to have a lot of this NPCs running around the map but idk how i should go about it.

I have also looked on more devforum posts about this topic but i never get a definitive response.

Thanks and have a good day!

I think the easiest way is to just increase the npc’s walkspeed.

Triangulation.

If a player is traveling x velocity in a certain direction, instead of moving toward the player The NPC can instead try to cut them off by going toward where they thing the user is going to end up.

Or use this if you absolutely want to hate yourself

try this, most people use it for chase pathfinding, including me

It was already on 23, changing it to 30 makes no difference.

@scooter_user @Kooraseru Thanks, ill check those options out and see what works out for me

Speed increase only really works if it’s able to actually catch up, from the looks of it, there is no leeway for it to continue on; basically instead of having it reach 100% have it lerp over dt

I’m really horrible at explaining, but basically it won’t continue to the next point until it has fully reached it’s current point. you need to tell it “hey, you can continue on! no need to fully reach it!”

Seems simple enought, ill try that out too

Since your character is a 2d image and doesn’t need animated also try to have it’s position handled like a point, and have it just tween or smth as it moves. That’s the nice thing about nextbots is the fact it won’t look wrong like how a 2d rig with no animations would look.

Should i also remove its humanoid? The model is based of 4 parts which is basically “Head”, “HumanoidRootPart”, “Decals” (The part that holds the decals) and “Hitbox” which is the only part with collision.
I had heard that humanoids are expensive but i cant recall it.

Try and and see if that helps.

Use raycast to detect current target, if raycast returns nil or an instance that’s not parented to player, it will use pathfinding, otherwise just do Humanoid:MoveTo(currentTarget.HumanoidRootPart.Position). Pathfinding takes a time to calculate, therefore it won’t able to catch up with player, regardless if it has insane speed due to it still follows old nodes, so not using pathfinding when target is very visible to npc would make npc move to target instantly and catch up.

But I would say your pathfinding code with pcall is very good.
Also, I advise to learn a difference between a loop and runservice, but I gonna tell one thing about it: loop runs once until it finishes while runservice makes code run in its own thread without waiting to finish, so it runs multiple times

Sorry for late response, anyways, thanks for telling me that about RunService, i wasnt sure about how it worked.

Also, i have another question, when i switch to pathfinding how should i handle it? Should i make a local conn = RunService.Heartbeat:Connect(function() and then when i need to use Pathfinding is simply use conn:Connect() or is there any better way of doing this?

No idea what are you talking about, but here’s example logic:

local NPC:Model = ...
local Path:Path = ...

local IsFollowing = false
local OldNodes

while true do
	task.wait(.2)

	local CurrentTarget:Model = ...
	
	local RaycastResult = workspace:Raycast(...)
	
	if RaycastResult ~= nil and RaycastResult.Parent:IsDescendantOf(CurrentTarget) ~= nil then
		IsFollowing = false
		OldNodes = nil

		NPC.Humanoid:MoveTo(CurrentTarget.HumanoidRootPart.Position)
	else
		if IsFollowing then continue end
		IsFollowing = true
		
		local Success = pcall(function()
			Path:ComputeAsync(NPC.HumanoidRootPart.Position, CurrentTarget.HumanoidRootPart.Position)
		end)
		
		if Success and Path.Status == Enum.PathStatus.Success then
			local Nodes = Path:GetWaypoints()
			OldNodes = Nodes
			
			task.spawn(function()
				for _, Waypoint in ipairs(Nodes) do
					if Nodes ~= OldNodes then return end
					
					if Waypoint.Action == Enum.PathWaypointAction.Jump then
						NPC.Humanoid.Jump = true
					end

					NPC.Humanoid:MoveTo(Waypoint.Position)
					NPC.Humanoid.MoveToFinished:Wait()
				end
				
				IsFollowing = false
			end)
		else
			IsFollowing = false
		end
	end
end

The reason why we put moving to nodes logic in a new thread is so it’s main loop won’t get delayed and keep continuing doing the raycast check, if raycast finds target, it sets OldNodes to nil, it would stop following the old nodes as you can see in code.)

It improved the system by a lot! Thanks for your help

a connection doesn’t return a signal connection. It returns two things. A boolean that tells you if the connection is connected and a disconnect method that let’s you stop the code running in your connection. For example:

local RunService = game:GetService("RunService")
local conn

conn = RunService.Heartbeat:Connect(function(deltaTime)
  print("The deltaTime is: " .. deltaTime)
end) --This will roughly print 60 times (I think)

task.wait(1)

print(conn.Connected) --prints true since the connection is still running

conn:Disconnect() --Now the code will stop running and the string won't print

print(conn.Connected) --prints false since we just disconnected the connection