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!