NPC pathfinds to player, but won't recalculate the path if it gets stuck on an object

  1. What do you want to achieve? Keep it simple and clear!
    I am trying to create a NPC that follows a player if it gets close enough.

  2. What is the issue?
    If my NPC gets caught on a block, or another part, it will not recalculate the path and find a way around it.

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I’ve tried to use Path.Blocked, but it doesn’t work. I have also looked at the documentation and other dev forums.

-- /SERVICES/
local Pathfinding_Service = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")

-- /VARIABLES/
local NPC_Char = script.Parent
local NPC_Root_Part = NPC_Char.HumanoidRootPart
local NPC_Humanoid = NPC_Char.Humanoid
local NPC_Params = {
	AgentRadius = 2.0,
	AgentHeight = 5.0,
	AgentCanJump = true
}
local Path = Pathfinding_Service:CreatePath(NPC_Params)
local Waypoints
local blockedConnection

-- /FUNCTIONS/
RunService.Stepped:Connect(function()
	local Maximum_Distance = 50

	for _, players in pairs(Players:GetPlayers()) do
		if players.Character then
			--print("character has been found")

			if players:DistanceFromCharacter(NPC_Root_Part.Position) <= Maximum_Distance then
				local success, errorMessage = pcall(function()
					Path:ComputeAsync(NPC_Root_Part.Position, players.Character.HumanoidRootPart.Position)
				end)
				if success and Enum.PathStatus.Success then
					--print("The player is in range of the NPC: ".. players.Name)
					Waypoints = Path:GetWaypoints()
					for _, waypoint in ipairs(Waypoints) do
						NPC_Humanoid:MoveTo(waypoint.Position)
					end
				end
			--else
				--warn("Player(s) is not with in range.")
			end
		end
	end
end)

Picture: https://gyazo.com/ad2e7a8f76bb30ec51aec7d1aed9b205?token=c39f7b991d7061756eed0ca5b56ad088

2 Likes

After your MoveTo, you need to add a MoveToFinished:Wait() to allow each move to complete:

NPC_Humanoid:MoveTo(waypoint.Position)
NPC_Humanoid:MoveToFinished:Wait()

If it is not reached within the timeout period (a maximum of 8 seconds by default) it will move to the next waypoint… You can add a number value to it to reduce the wait timeout.

1 Like