I’ve created a pathfinding NPC that travels to “idle points” when no player is within 150 studs of it. It travels between these points flawlessly until coming to a complete stop for seemingly no reason.
It happens suddenly and doesn’t slow to a stop. It will stutter and start to travel very, very, very slowly.
local Pathfinding = game:GetService("PathfindingService")
local Humanoid = script.Parent.Humanoid
local Torso = script.Parent:FindFirstChild("HumanoidRootPart")
local destination
local randomPathObject = nil
local interupt = false
local destinationChanged = false
local olddestination = nil
local chasing = false
local isRunningPath = false
local walkPath = function(waypoints) -- Iterate through waypoints until the path finishes
print("path started")
for _, waypoint in pairs(waypoints) do
isRunningPath = true
Humanoid:MoveTo(waypoint.Position)
print("waypoint interation")
if interupt then
interupt = false
isRunningPath = false
break
end
if waypoints.Action == Enum.PathWaypointAction.Jump then
Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
Humanoid.MoveToFinished:Wait()
end
randomPathObject = nil
pathComplete = true
chasing = false
isRunningPath = false
print("path finished")
end
local function updateDestination() -- Manage destinations
while nil ~= script.Parent do
local PlayerCharacter,Magnitude = getNearestPlayer()
wait(.1)
if PlayerCharacter == nil or Magnitude == nil then
else
olddestination = destination
local PlayerCharacter = game.Workspace:FindFirstChild(PlayerCharacter)
if Magnitude >= 150 and randomPathObject == nil and chasing == false then
randomPathObject = nil
chasing = false
local items = game.Workspace.Map.NPC:GetChildren()
randomPathObject = items[math.random(1,#items)]
destinationChanged = true
destination = randomPathObject.Position
print("found idle destination")
end
if Magnitude < 150 and chasing == false then
randomPathObject = nil
chasing = false
destinationChanged = true
destination = PlayerCharacter.HumanoidRootPart.Position
chasing = true
print("found player destination")
end
end
end
end
spawn(updateDestination)
local function takeDestinationAndRunPath() -- Pathfind to the destinations
while wait() do
repeat wait() until destination ~= nil
if destinationChanged then
destinationChanged = false
print("new destination recieved")
if isRunningPath then
interupt = true
repeat wait() until interupt == false
print("old path stopped")
end
local path = Pathfinding:CreatePath()
path:ComputeAsync(Torso.Position, destination)
local waypoints = path:GetWaypoints()
pathComplete = false
spawn(function() walkPath(waypoints) end)
print("setting up new path")
end
end
end
spawn(takeDestinationAndRunPath)
The following video demonstrates the issue
This is my first ever script I’ve made with pathfinding, so please feel free to call out any bad practice.
Thank you in advance.