Pathfinding Not Working

I’m trying to make a pathfinding system for NPC’s where they reach the end position using predefined nodes, I have this so far but it stops randomly with no errors or anything. Not sure why it does this.

Here’s the code -

local PathfindingService = game:GetService("PathfindingService")
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")

local nodeFolder = workspace.Nodes

local nodePositions = {}

for _, nodePart in ipairs(nodeFolder:GetChildren()) do
	if nodePart:IsA("BasePart") then
		table.insert(nodePositions, nodePart.Position)
	end
end

local path = PathfindingService:CreatePath()

local function followPath(destination)
	local success, errorMessage = pcall(function()
		path:ComputeAsync(character.PrimaryPart.Position, unpack(nodePositions), destination)
	end)

	if success and path.Status == Enum.PathStatus.Success then
		local waypoints = path:GetWaypoints()

		local moveFinishedEvent = Instance.new("BindableEvent")
		local moveFinishedConnection

		-- Move NPC along the path
		for i, waypoint in ipairs(waypoints) do
			moveFinishedConnection = humanoid.MoveToFinished:Connect(function(reached)
				if reached then
					moveFinishedEvent:Fire()
				end
			end)

			humanoid:MoveTo(waypoint.Position)
			moveFinishedEvent.Event:Wait()

			moveFinishedConnection:Disconnect()
		end

		moveFinishedEvent:Destroy()
	else
		warn("Path not computed!", errorMessage)
	end
end

local destination = Vector3.new(nodeFolder.End.Position)
followPath(destination)

Here’s a video -

2 Likes

Shouldnt you use pairs instead of ipairs?

I’ve seen lots of posts on the forums about this same subject.
There’s probably an answer in one of those that would help you out. There may be other information as well that you could learn from.

same for that too btw. charchar

I’m not an pathfinding expert but it always helps to see what the code sees. Try adding a display waypoints function

local PathFolder = instance.new("Folder", workspace)
PathFolder:ClearAllChildren()

-- Loop through waypoints
for _, waypoint in pairs(waypoints) do
    local part = Instance.new("Part")
    part.Shape = "Ball"
    part.Material = "Neon"
    part.Size = Vector3.new(0.6, 0.6, 0.6)
    part.Position = waypoint.Position
    part.Anchored = true
    part.CanCollide = false
    part.Parent = PathFolder
end
1 Like

This definitely helps, it has to do with the pathfinding computation because the display ends at that point, thanks.

1 Like

Does it look at all like this?

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.