Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I use Pathfinding?

How would I make it work with an npc?

2 answers

✓ Accepted answer

Create a script inside of ServerScriptService and put this code into it:

local pathfindingService = game:GetService("PathfindingService")
local pointModel = Instance.new("Model")
pointModel.Name = "Points"
pointModel.Parent = game.Workspace

-- Setup remote function
local remoteFunction = Instance.new("RemoteFunction")
remoteFunction.Parent = game.ReplicatedStorage

function visualizePath(path)
	-- clear old path visualization
	for _, point in pairs(pointModel:GetChildren()) do
		point:Destroy()
	end
		
	-- calculate new visualization	
	local points = path:GetPointCoordinates()
	for _, point in pairs(points) do
		local part = Instance.new("Part")
		part.Parent = pointModel
		part.FormFactor = Enum.FormFactor.Custom
		part.Size = Vector3.new(1,1,1)
		part.Position = point
		part.Anchored = true
		part.CanCollide = false
	end
end

game.ReplicatedStorage.RemoteFunction.OnServerInvoke = function(player, target)
	local start = player.Character.Torso.Position
	local path = pathfindingService:ComputeRawPathAsync(start, target, 500)
 
	visualizePath(path)
	-- Check to see if the path was computed correctly
	if path.Status == Enum.PathStatus.FailStartNotEmpty or path.Status == Enum.PathStatus.FailFinishNotEmpty then
		print("Compute failed")
		return {}
	end
	
	return path:GetPointCoordinates()		
end

Then make a Local Script and put it into Starter Pack and put this code in it:

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
 
local followingPath = false
mouse.Button1Down:connect(function()
	if not followingPath then
		followingPath = true
		
		-- Ask the server to calculate a path for us
		local points = game.ReplicatedStorage.RemoteFunction:InvokeServer(mouse.Hit.p)
			
		for _, point in pairs(points) do
			print("moving to: ", point)
			player.Character.Humanoid:MoveTo(point)
			-- Don't try moving to the next point until we are close enough to the current point in the path
			repeat
				distance = (point - player.Character.Torso.Position).magnitude
				wait()
			until distance < 3
		end
		followingPath = false
	end
end)

For more information go too the Roblox Wiki and search up PathFinding.

This discussion is preserved as it was. New answers, comments, and votes are closed.