1. Create the PathfindingService Instance
Before using pathfinding, you need to access the PathfindingService.
local PathfindingService = game:GetService("PathfindingService")
2. Define Start and Goal Positions
You need to specify where the NPC is starting from and where it should go.
local startPosition = NPC.HumanoidRootPart.Position
local goalPosition = Target.Position -- Target could be a storage area, tree, etc.
3. Create a Path Object
Use the CreatePath function to generate a path object.
local path = PathfindingService:CreatePath({
AgentRadius = 2, -- Adjust based on NPC size
AgentHeight = 5,
AgentCanJump = true,
AgentJumpHeight = 7,
AgentMaxSlope = 45
})
4. Compute the Path
The ComputeAsync function calculates a path from start to goal.
path:ComputeAsync(startPosition, goalPosition)
5. Check If the Path Is Computed Successfully
Use GetStatus() to ensure the path is valid.
if path.Status == Enum.PathStatus.Success then
print("SUCCESS!")
end
6. Get Waypoints and Move NPC
If the path is valid, retrieve the waypoints and guide the NPC along them.
local waypoints = path:GetWaypoints()
for _, waypoint in pairs(waypoints) do
NPC.Humanoid:MoveTo(waypoint.Position)
NPC.Humanoid.MoveToFinished:Wait()
end
7. Handle Path Updates and Errors
If the path is blocked or changes, you may need to recalculate it.
path.Blocked:Connect(function(blockedIndex)
print("Path is blocked! Recalculating...")
path:ComputeAsync(NPC.HumanoidRootPart.Position, goalPosition)
end)
Example Of Full Script Including These Steps.
local PathfindingService = game:GetService("PathfindingService")
local function moveNPC(NPC, Target)
local path = PathfindingService:CreatePath({
AgentRadius = 2,
AgentHeight = 5,
AgentCanJump = true,
AgentJumpHeight = 7,
AgentMaxSlope = 45
})
path:ComputeAsync(NPC.HumanoidRootPart.Position, Target.Position)
if path.Status == Enum.PathStatus.Success then
local waypoints = path:GetWaypoints()
for _, waypoint in pairs(waypoints) do
NPC.Humanoid:MoveTo(waypoint.Position)
NPC.Humanoid.MoveToFinished:Wait()
end
else
warn("Failed to generate a path!")
end
end
local NPC = workspace.NPC -- Replace with your NPC
local Target = workspace.Target -- Replace with your target destination
moveNPC(NPC, Target)