Problem with pathfinding service

Hello, I am using pathfinding service for my game and I came across a problem. When I move a part to block the path, the NPC moves all the way back to where they started and then starts moving toward the target again. Here is a video of it happening:
https://gyazo.com/acfd3a64a244b4dc14017995002b5bec

I found this code here:

local function moveNPC(npc, start, endpoint)
	local path = PFS:CreatePath()	
	local waypoints, currentWaypointIndex
	local humanoid = npc.Humanoid
	local function followPath(destination)
		path:ComputeAsync(start, endpoint)
		waypoints = {}
		if path.Status == Enum.PathStatus.Success then
			waypoints = path:GetWaypoints()
			currentWaypointIndex = 1
			humanoid:MoveTo(waypoints[currentWaypointIndex].Position)
		else
			humanoid:MoveTo(npc.HumanoidRootPart.Position)
		end
	end
	
	local function onWaypointReached(reached)
		if reached and currentWaypointIndex < #waypoints then
			currentWaypointIndex = currentWaypointIndex + 1
			humanoid:MoveTo(waypoints[currentWaypointIndex].Position)
		end
	end

	local function onPathBlocked(blockedWaypointIndex)
		if blockedWaypointIndex > currentWaypointIndex then
			followPath()
		end
	end
	
	path.Blocked:Connect(onPathBlocked)

	humanoid.MoveToFinished:Connect(onWaypointReached)

	followPath()
end

.
I am pretty sure that the problem is coming from this part:

if path.Status == Enum.PathStatus.Success then
	waypoints = path:GetWaypoints()
	currentWaypointIndex = 1
	humanoid:MoveTo(waypoints[currentWaypointIndex].Position)
else
	humanoid:MoveTo(npc.HumanoidRootPart.Position) --This line here
end

Thanks for reading!

1 Like

Perhaps making it recursive might work? (^▽^)

	local function followPath(destination)
		path:ComputeAsync(start, endpoint)
		waypoints = {}
		if path.Status == Enum.PathStatus.Success then
			waypoints = path:GetWaypoints()
			currentWaypointIndex = 1
			humanoid:MoveTo(waypoints[currentWaypointIndex].Position)
		else
			followPath(destination)
		end
	end

Thank you so much that works! I also realized that each time I was computing the path from the original start position, not from where the NPC was currently at, so changing both of those fixed it.

1 Like