Issue with my pathfinding script

local npc = script.Parent
local PathfindingService = game:GetService("PathfindingService")
local RunService = game:GetService("RunService")

local humanoid = npc:WaitForChild("Humanoid")
local humanoidRootPart = npc:WaitForChild("HumanoidRootPart")
local animator = humanoid:WaitForChild("Animator")

--// Animations
local animations = {
	Idle = 507766388,
	Walk = 913402848,
	Run = 14886224685,
}

local animTracks = {}
for name, id in pairs(animations) do
	local anim = Instance.new("Animation")
	anim.AnimationId = "rbxassetid://" .. id
	animTracks[name] = animator:LoadAnimation(anim)
	animTracks[name].Priority = Enum.AnimationPriority.Action
end

local currentState = "Idle"
local function setAnimation(state)
	if currentState == state then return end
	if animTracks[currentState] and animTracks[currentState].IsPlaying then
		animTracks[currentState]:Stop(0.2)
	end
	if animTracks[state] then
		animTracks[state].Looped = true
		animTracks[state]:Play()
	end
	currentState = state
end


local function getRandomWaypoint()
	local folder = workspace:FindFirstChild("SurvivorWaypoints")
	if not folder then return nil end
	local waypoints = folder:GetChildren()
	if #waypoints == 0 then return nil end
	return waypoints[math.random(1, #waypoints)]
end


local function moveToPosition(targetPos, speed)
	local path = PathfindingService:CreatePath({
		AgentRadius = 2,
		AgentHeight = 5,
		AgentCanJump = true,
	})
	path:ComputeAsync(humanoidRootPart.Position, targetPos)
	local waypoints = path:GetWaypoints()

	if path.Status == Enum.PathStatus.Success then
		humanoid.WalkSpeed = speed
		for _, waypoint in ipairs(waypoints) do
			humanoid:MoveTo(waypoint.Position)
			if waypoint.Action == Enum.PathWaypointAction.Jump then
				humanoid.Jump = true
			end
			local reached = humanoid.MoveToFinished:Wait()
			if not reached then break end
		end
	end
end


local function goToRandomWaypoint(state)
	local waypoint = getRandomWaypoint()
	if not waypoint then
		setAnimation("Idle")
		return
	end
	setAnimation(state)
	moveToPosition(waypoint.Position, state == "Run" and 20 or 10)
	setAnimation("Idle")
end

-- Check for nearby clowns using GamePlayerStatus
local function getNearestClown(maxDistance)
	local nearest, nearestDist = nil, maxDistance
	local statusFolder = workspace:FindFirstChild("GamePlayerStatus")
	if not statusFolder then return nil end

	for _, value in pairs(statusFolder:GetChildren()) do
		if value:IsA("StringValue") and value.Value == "Clown" then
			local playerName = value.Name
			local player = game.Players:FindFirstChild(playerName)
			if player and player.Character and player.Character:FindFirstChild("HumanoidRootPart") then
				local dist = (player.Character.HumanoidRootPart.Position - humanoidRootPart.Position).Magnitude
				if dist < nearestDist then
					nearest = player.Character
					nearestDist = dist
				end
			end
		end
	end

	return nearest
end

-- Main behavior loop
task.spawn(function()
	-- Initial random waypoint
	goToRandomWaypoint("Walk")

	while humanoid.Health > 0 do
		local nearbyClown = getNearestClown(50)

		if nearbyClown then
			-- Run to new random waypoint when a clown is close
			goToRandomWaypoint("Run")
		end

		-- Wait a bit before checking again, survivor stays hidden if no clown
		task.wait(1)
	end
end)

This is my NPC script, this is a hide and seek style game. I have the NPC pathfind to a random waypoint on the map. Once he gets there, he sits still. Until a clown (enemy) comes within 50 studs of him, and then he goes into panic mode and runs towards a new way point. This works, but if the clown chases him, after like 30 seconds the NPC starts to bog down and eventually just freezes entirely. Any idea whats wrong here?

Hey Matt!

Thank you for posting on our forum.

I understand that you have an NPC that runs away from an enemy (clown). But he gets stuck while he runs away from the clown.

I reviewed your code, and I see that it is a script under the NPCs model. At first glance, I do not see any hard-coded logical issues.

I have some questions for you that might help you identify the problem you have.

  • Are there many obstacles? The pathfinding settings for your NPC might not be compatible with the map. Maybe you can try this on a baseplate without obstacles and see if the problem persists. If it doesn’t, then you need to tweak your pathfinding settings/configuration.
  • Is the clown’s magnitude from the NPC above, equal to, or lower than 50 studs when he gets stuck? You can print out the magnitude.
  • Have you tried printing every action your script takes? This is a debugging technique to see the last action being taken before your NPC gets stuck.

I hope this helps you troubleshoot the issue and hopefully fix it!

Why does it looks AI? @Phylixius

Why do you spawn a useless thread?

Please avoid use of ipairs/pairs and use generic iteration instead.

FORGPREP_(INEXT/NEXT) are slow.

Please cache as much things possible and especially services, use auto complete plugin if you can’t write them manually:
https://create.roblox.com/store/asset/11380642657

Also please cache “configs” table stuff:

Make sure to preload and cache animation tracks instead of recompiling them every time (mega expensive)

Edit: yeah i see now you do cache them but its good to make table like:

local _temp = Instance.new("Animation")
_temp.AnimationId  = "rbxassetid://507766388"
local animTracks  = {
["rbxassetid://507766388"] = animator:LoadAnimation(_temp)
}
_temp:Destroy()

Don’t use concat operation in runtime please unless it can be inlined by compiler into final string (it can’t in this case)

What if using like, it might like used once and that’s it ?
try change main behaviour to loop

while task.wait() do

end

The problem could be MoveToFinished, according to the API:

If the Humanoid reaches its goal within 8 seconds, this event will return with reached as true. If the goal is not reached within 8 seconds the Humanoid will stop walking and reached will be false. This timeout can be reset be calling Humanoid:MoveTo() again within the timeout period.

A possible solution is to run goToRandomWaypoint in a separate thread so that it does not block the main loop.

local isBusy = false --prevents the NPC from attempting to do two things at once
local function goToRandomWaypoint(state)
	if isBusy then return end
	isBusy = true

	local waypoint = getRandomWaypoint()
	if not waypoint then
		setAnimation("Idle")
		isBusy = false 
		return
	end

	setAnimation(state)
	moveToPosition(waypoint.Position, state == "Run" and 20 or 10)
	setAnimation("Idle")

	isBusy = false
end
task.spawn(function()
	while humanoid.Health > 0 do
		if not isBusy then
			local nearbyClown = getNearestClown(50)

			if nearbyClown then
				task.spawn(goToRandomWaypoint, "Run")
			else
				task.spawn(goToRandomWaypoint, "Walk")
			end
		end

		task.wait(1)
	end
end)