Lesson 9 of 12
NPCs and pathfinding: the scrap crawler
Make a Roblox NPC that walks around obstacles. Build Beacon Yard's scrap crawler with PathfindingService, waypoints, blocked events, re-pathing, costs and modifiers, a state machine, and server-side performance.
By the end you can
- Compute a path with PathfindingService, tune the agent parameters, and walk a Humanoid along its waypoints
- Handle blocked paths and a moving target by re-pathing, without re-pathing every frame
- Steer paths with material costs, PathfindingModifier regions and links
- Drive an NPC with a small state machine and keep it cheap and server-owned
Before this: The drone: movement, targeting, damage, Animation: the Animation Editor, Moon Animator, Animator
1Flying is easy; walking is not
The drone has it easy. It hovers 4 studs up and glides in a straight line toward the nearest player, through anything in the way. It can do that because it is anchored, moved by the server, and nothing in the yard is tall enough to matter.

Select a numbered pin, or a row below, to read what it marks.
The drone flies straight at you. The crawler added in m08-crawler walks, so it has to go around things.
Milestone m08-crawler adds a second enemy: the scrap crawler, a low ground robot that walks. It is a rig with a Humanoid, so it falls, collides and climbs like a character. Walking in a straight line, it would push into the first crate it met and stay there. It needs a plan.
Suppose the crawler copied the drone's movement: each frame, step straight toward the nearest player. A crate stands between them. What happens?
Answer
The crawler walks into the crate and stays stuck against it. A Humanoid is physically simulated and blocked by solid parts. Steering straight at a target only works when nothing is in the way; walking NPCs need a path.
Open this step in lesson mode · Link to this step · This confused me
2Ask PathfindingService for a path
PathfindingPathfindingFinding a walkable route around obstacles from one point to another.Think of it as a sat-nav that plans around closed roads. is the job of finding a walkable route around obstacles. Roblox does it for you with PathfindingService1. You describe the walker, the agent, once with CreatePath, then call ComputeAsync(start, goal) whenever you need a route.
| Agent parameter | What it means | Default |
|---|---|---|
AgentRadius | How much room the agent needs from obstacles, in studs | 2 |
AgentHeight | Gaps lower than this are not walkable | 5 |
AgentCanJump | Whether the path may include jumps | true |
AgentCanClimb | Whether it may climb TrussParts | false |
WaypointSpacing | Distance between intermediate waypoints | 4 |
Costs | How much to avoid materials or labelled regions | none |
local PathfindingService = game:GetService("PathfindingService")
local path = PathfindingService:CreatePath({
AgentRadius = 2,
AgentHeight = 3,
AgentCanJump = true,
AgentCanClimb = false,
WaypointSpacing = 4,
})
local ok = pcall(function()
path:ComputeAsync(root.Position, target.Position)
end)
if ok and path.Status == Enum.PathStatus.Success then
local waypoints = path:GetWaypoints()
end
ComputeAsync yields and can fail, so it is wrapped in pcall, and Status says whether a path was found. In m08-crawler, CrawlerBrain.agentParams() returns those exact values: radius 2 and height 3, matching a low crawler that can still squeeze through the same gaps as a player, with jumping on and climbing off. You can also pass a Costs table (covered in a moment) when you want it to avoid a material or region.
Two crates stand 4 studs apart. The crawler keeps trying to squeeze between them and getting wedged. Which parameter should you raise?
Answer
AgentRadius. AgentRadius is the clearance the agent needs from obstacles. A radius that matches the crawler's real width makes the pathfinder route around the narrow gap instead.
Open this step in lesson mode · Link to this step · This confused me
3Walk the waypoints
A path is a list of waypoints, each a Position plus an Action: Walk, or Jump where the route needs a hop. Roblox's pathfinding guide follows a path with Humanoid:Move: point the humanoid at the next waypoint, check every frame whether it has arrived, then move on. A jump waypoint calls Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)1.
local RunService = game:GetService("RunService")
local REACH = 2 -- studs, measured on the ground plane
local GIVE_UP = 8 -- seconds per waypoint
local function follow(humanoid: Humanoid, waypoints: { PathWaypoint })
local root = humanoid.RootPart
if root == nil then
return false
end
for index = 2, #waypoints do
local waypoint = waypoints[index]
if waypoint.Action == Enum.PathWaypointAction.Jump then
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
local started = os.clock()
while true do
local offset = waypoint.Position - root.Position
if Vector3.new(offset.X, 0, offset.Z).Magnitude < REACH then
break
end
if os.clock() - started > GIVE_UP then
humanoid:Move(Vector3.zero)
return false
end
humanoid:Move(offset)
RunService.Heartbeat:Wait()
end
end
humanoid:Move(Vector3.zero)
return true
end
The loop starts at 2 because waypoint 1 is where the agent already stands.
There is a second way to walk, and it is the one Beacon Yard's crawler uses. Humanoid:Move takes a direction and keeps walking that way until you call it again. Humanoid:MoveTo takes a point: the humanoid walks there and stops on arrival. MoveTo gives up after 8 seconds if the goal is never reached, and MoveToFinished then fires with false; calling MoveTo again resets that timer2. Move has no timer, so the loop above brings its own.
The crawler's loop runs ten times a second, not every frame. Between ticks a Move direction would carry it past a waypoint; a MoveTo point stops it there. So CrawlerService.follow calls MoveTo on each tick, never waits for MoveToFinished, and advances when it is within CRAWLER_REACH of the waypoint. For a jump waypoint it sets Humanoid.Jump = true, which does the same job as ChangeState(Jumping).
local function follow(crawler: Crawler, target: Vector3)
local root = crawler.root
local waypoint: PathWaypoint? = crawler.waypoints[crawler.nextIndex]
if waypoint ~= nil and flatDistance(waypoint.Position, root.Position) < Config.CRAWLER_REACH then
crawler.nextIndex += 1
waypoint = crawler.waypoints[crawler.nextIndex]
end
if waypoint == nil then
-- The path is used up, and the target has not moved far enough
-- to be worth a new one. Close the last few studs directly.
crawler.humanoid:MoveTo(target)
return
end
if waypoint.Action == Enum.PathWaypointAction.Jump then
crawler.humanoid.Jump = true
end
crawler.humanoid:MoveTo(waypoint.Position)
Go deeper Why not MoveTo straight to the player?
Humanoid:MoveTo walks in a straight line toward one point. It does not plan, so it has the same problem as the drone: the first crate stops it. Pathfinding turns one far goal into many short straight walks that are each known to be clear.
Put one chase in order.
Answer
1. CreatePath with the crawler's agent parameters (once) 2. ComputeAsync from the crawler's root to the target 3. Check that Status is Success and read GetWaypoints 4. Walk toward the next waypoint (Move or MoveTo) until it is reached 5. Repeat until the last waypoint, or re-path if something changed. Create the path object once per crawler, compute, check, then walk waypoint by waypoint, and go back to computing when the world or the target changes.
Open this step in lesson mode · Link to this step · This confused me
4See the search
The path service searches a navigation mesh, a map of where an agent of your size can stand. You can see it in Studio: turn on Navigation mesh in the viewport's Visualization Options. The simulation below shrinks the idea to a grid so you can watch it work.
The pathfinding grid

A top-down grid of the yard. Drag crates, paint a costly strip, set the agent radius, and step the crawler along its waypoints. Each square shows the cost the search paid to reach it.
In the simulation, you raise the agent radius from 1 square to 2. A one-square gap between two crates was on the old path. What does the new path do?
Answer
It goes around both crates, because the gap is now too narrow. A bigger agent needs more clearance, so narrow gaps disappear from the walkable area and the search routes around them.
Open this step in lesson mode · Link to this step · This confused me
5Blocked paths and moving targets
The yard changes while the crawler walks. A gate slides shut, a crate is knocked over, and the player keeps running. Two things trigger a new ComputeAsync:
path.Blockedfires with the index of a waypoint that something now covers. Re-path only if that index is at or ahead of the waypoint you are walking to; a block behind you does not matter1.- The target moved. A path to where the player was goes stale. Re-path when the target has moved far enough, but not more often than a minimum interval.
local MIN_INTERVAL = 0.5
local REPATH_DISTANCE = 6
local lastPathAt = 0
local paths = 0
-- time, how far the target moved since the last path, blocked ahead?
local frames = {
{ 0.1, 8, false }, { 0.6, 8, false }, { 0.7, 1, false },
{ 0.8, 0, true }, { 2.0, 2, false }, { 2.1, 7, false },
}
for _, f in frames do
local now, moved, blocked = f[1], f[2], f[3]
if blocked or (now - lastPathAt >= MIN_INTERVAL and moved >= REPATH_DISTANCE) then
lastPathAt = now
paths += 1
print("re-path at", now)
end
end
print("paths", paths)
re-path at 0.6
re-path at 0.8
re-path at 2.1
paths 3With ten crawlers, the server's frame time spikes. Which line is the problem?
RunService.Heartbeat:Connect(function()
for _, crawler in crawlers do
crawler.path:ComputeAsync(crawler.root.Position, crawler.target.Position)
end
end)
Answer
Line 3: crawler.path:ComputeAsync(crawler.root.Position, crawler.target.Position). Fixed: Re-path only when blocked or when the target moved far enough, at most every 0.5 seconds per crawler. ComputeAsync is a search, and this asks for 600 a second. Re-path on events and with a throttle, and stagger crawlers so they do not all search on the same frame.
Open this step in lesson mode · Link to this step · This confused me
6Costs, modifiers and links
By default the path service returns the shortest path. Usually you want the sensible one. Three tools steer it1:
- Material costs.
Costs = { Neon = 4 }makes walking on Neon four times as expensive, so the crawler prefers to go around it. Every material costs 1 by default, andmath.hugemakes one unwalkable. PathfindingModifier. Put one inside an invisible, anchored, non-colliding part and give it aLabel, such asHazard. AddHazard = 10toCostsand the whole region becomes expensive, whatever it is made of. WithPassThroughon, the search treats a solid part, like a closed gate, as open.PathfindingLink. Joins two attachments the agent cannot walk between, such as across a gap, with aLabelyour code reacts to when the agent reaches it.
The yard already has a candidate: MapBuilder lays a 16-stud Neon Hazard stripe in front of the north gate.
Think of cost as length × material cost. Route A crosses 10 studs of Neon (cost 4). Route B walks 30 studs of plain asphalt (cost 1). What is the cost of the cheaper route?
Answer
30. A costs 40 and B costs 30, so the crawler takes the longer, cheaper route around the stripe. This is a mental model of what Costs does, not the engine's exact sum.
Open this step in lesson mode · Link to this step · This confused me
7A crawler is a small state machine
Pathfinding answers how to get somewhere. The crawler also needs to decide what to do. Like the round, it is a state machine: Idle, Chase, Attack and Stunned, re-evaluated a few times a second on the server.
Server sideRemember: A round state machine is a traffic light.
| State | Becomes | When |
|---|---|---|
| any | Stunned | A wrench hit lands |
| Stunned | Idle | The stun time has passed |
| Idle or Chase | Attack | A living player is within 4 studs |
| Idle | Chase | A living player is within 40 studs and a path exists |
| Chase | Idle | The target is gone, or no path can be found |
Each transition has side effects. Entering Chase computes a path. Entering Stunned stops the walk in progress (calling humanoid:Move(Vector3.zero) in the Move pattern, or humanoid:MoveTo(root.Position) in m08-crawler's MoveTo loop). Leaving Attack starts a damage cooldown, like the drone's.
The crawler is in Attack, a player is 2 studs away, and a wrench hit stuns it this tick. Using the table, what state is it in next?
-- facts this tick
local stunned = true
local targetDistance = 2
Answer
Stunned. Stunned wins from any state. The rule order is part of the design: check the strongest condition first, or a stunned crawler keeps biting.
Open this step in lesson mode · Link to this step · This confused me
8Keep it on the server, and keep it cheap
The crawler's brain runs on the server, so its decisions cannot be faked. Its body is the catch. A Humanoid is unanchored, and the engine hands physics of unanchored parts near a player to that player's device3. That player could then move your NPC.
| In the picture | In Roblox |
|---|---|
| Holding the ball | Simulating an assembly's physics |
| Passing to the nearest player | The engine's automatic ownership near a character |
| The referee taking the ball back | SetNetworkOwner(nil) on the server |
Network ownership is who is holding the ball. Whoever holds it decides where it goes. By default, the engine passes the ball of a loose part to the nearest player.
Think of it as Whoever holds the ball
So the crawler's spawn code calls root:SetNetworkOwner(nil): the server keeps the ball. The Roblox docs warn to do this sparingly because it can look less smooth for players, which is the right trade for an enemy.
The rest is budget. Run every crawler from one Heartbeat loop instead of a script each. Re-think a few times a second, not every frame. Throttle and stagger ComputeAsync. Cap how many crawlers exist. Each Humanoid costs more than a plain part, so a crowd of fifty would use a lighter body.
Which choices keep ten crawlers cheap and fair on the server?
Answer
One loop that updates every crawler, instead of one script per crawler; SetNetworkOwner(nil) on each crawler's root; Re-path on Blocked or when the target moves 6 studs, at most every 0.5 seconds. One loop, server ownership and throttled re-pathing are the standard pattern. Path searches every frame waste the server, and client-run enemies can be cheated.
Open this step in lesson mode · Link to this step · This confused me
9Build it: the crawler in m08-crawler
Other ways pros do this
| Option | What it is | When pros pick it | Trade-offs |
|---|---|---|---|
| PathfindingService | Roblox's built-in navigation mesh and search. | Most walking NPCs in most games. What the crawler uses. | A path search per request, and you write the following, re-pathing and stuck detection yourself. |
| Steering only | Move straight toward the target, maybe with raycasts to slide along walls. | Flyers like the drone, open arenas, swarms of cheap enemies. | Gets stuck behind anything it cannot see around. |
| A hand-rolled grid search (A*) | Your own grid of the level and an A* search over it. | Grid games, tower defence, or when you need full control over costs. | You keep the grid in sync with the world yourself. |
| Community path-following modules | Open-source wrappers that add waypoint following, re-pathing and stuck checks around PathfindingService. | Teams that want the follow loop solved and reviewed. | Another dependency to vet; read the code before you trust it. |
Build along
src/server/CrawlerService.luausrc/server/CrawlerBrain.luausrc/server/MapBuilder.luausrc/server/init.server.luausrc/shared/Config.luau
Check out
m08-crawler, runrojo serve, press Play, open Visualization Options at the top right of the viewport, and turn on Navigation mesh and Pathfinding modifiers.You should see Studio's viewport shows coloured walkable areas across the yard floor, with gaps around the walls, gates, pedestal, shop and scrap stacks.
Inspect
git diff --stat m07-feel m08-crawler -- srcand opensrc/server/init.server.luau,src/server/CrawlerBrain.luauandsrc/server/CrawlerService.luau.You should see CrawlerService.luau and CrawlerBrain.luau exist, and init.server.luau calls CrawlerService.start({ spawn = map.crawlerSpawn, container = map.yard }) after DroneService.
Start a drill and watch the crawler spawn from the south-west corner with
SetNetworkOwner(nil)on its root and follow waypoints fromCrawlerBrain.agentParams().You should see During a drill, one crawler spawns in the south-west corner at CrawlerSpawn (-34, 2.5, -34), navigates around the scrap stacks and pedestal toward the nearest player, and stops in attack range.
Lead the crawler around the scrap stacks and watch
CrawlerBrain.shouldRepathandpath.Blockedtrigger a fresh path without spamming every frame.You should see Walking around a scrap stack makes the crawler re-path within about half a second without returning to its spawn.
Open this step in lesson mode · Link to this step · This confused me
10Where the traffic light breaks
A traffic light changes on a timer. The crawler's states change on events: a hit, a path that fails, a player who leaves. And some transitions do work as they happen. Answer first, then open it.
Where does it break?“A traffic light” is a good picture of a round state machine. Where does it stop being true?
It breaks here. A traffic light only changes on a timer, but real transitions have conditions (a press, everyone down, a path blocked) and side effects (gates, lighting, re-pathing) that must run exactly once.
The true model. A state machine is a current state plus a set of transitions. Each transition has a guard condition and side effects. One owner changes the state and publishes it, so no other code can put it in an impossible combination.
A bug report says a stunned crawler slides another few studs before stopping. Which side effect is missing on entering Stunned?
Answer
Cancelling the walk in progress (humanoid:Move(Vector3.zero), or MoveTo(root.Position) if using MoveTo). Changing a state variable does not stop the body. Entering Stunned has to cancel the walk; that is the side-effect half of a transition.
Open this step in lesson mode · Link to this step · This confused me
11Challenges
Level 2, Builder
Challenge
Add a PathfindingModifier over the gate's Hazard stripe and show that a cost changes the route.
- Start from
- The game at milestone m08 (download)
Done means
- A path computed across the Hazard stripe now goes around it
- The modifier part is invisible, anchored and non-colliding
- Removing Hazard from Costs makes the path cross the stripe again
Hints
- m08-crawler ships the Neon Hazard stripe without a PathfindingModifier; add an invisible, anchored, CanCollide = false part over it with a PathfindingModifier labelled Hazard.
- Compute a test path from the command bar between (0, 3, 30) and (0, 3, 44) with Costs = { Hazard = 10 } and print each waypoint's position.
The gates are closed in Idle. You want the crawler to plan through the gate anyway and wait there until it opens. What do you add?
Answer
A PathfindingModifier with PassThrough on, in a part around the gate. PassThrough lets the search treat the gate as open, so the path goes through it. The crawler then has to wait at the gate until the round opens it.
Level 3, Professional
Challenge
Write the crawler's brain as two pure functions matching m08-crawler's CrawlerBrain. Start from the m14-ship tag in the game repo to get challenges/npc_pathfinding_work.luau and challenges/npc-pathfinding.luau, edit challenges/npc_pathfinding_work.luau, and run game.ServerScriptService.RunGameTests:Invoke("npc-pathfinding") from the command bar.
- Start from
- The game at milestone m14 (download)
- Grade it
- In Studio, press Play, then run
game.ServerScriptService.RunGameTests:Invoke("npc-pathfinding")in the server command bar. Copy the pass code from Output.
Done means
- challenges/npc_pathfinding_work.luau implements nextState(state, facts) for the crawler's state table (stun overrides all, finished stun recovers to Idle, Attack <= 4 studs, Chase <= 40 studs, failed path or missing target goes Idle)
- Its shouldRepath(now, lastPathAt, targetMoved, blockedAhead) re-paths immediately when blockedAhead is true, or when now - lastPathAt >= 0.5 and targetMoved >= 6
- challenges/npc-pathfinding.luau prints TEST PASS for every check
Hints
- Check the strongest condition first: stunned beats everything.
- A failed path means give up and go Idle.
- Throttle first, then distance; a block ahead skips the throttle.
Open this step in lesson mode · Link to this step · This confused me
12Recap
Recap
- Describe the agent once with CreatePath, compute with ComputeAsync inside pcall, check Status, then walk to each waypoint until you reach it: Move with a direction every frame, or MoveTo with a point on a slower tick, as the crawler does.
- Re-path when Blocked fires ahead of you or the target moves far enough, with a throttle; steer routes with Costs, PathfindingModifier regions and links.
- The crawler is a server-side state machine whose transitions have side effects, with SetNetworkOwner(nil) on its root and one budgeted update loop.
A round state machine is a traffic light, until a traffic light only changes on a timer, but real transitions have conditions (a press, everyone down, a path blocked) and side effects (gates, lighting, re-pathing) that must run exactly once.
Network ownership is whoever holds the ball, until the server can take the ball back at any time and always keeps anchored parts, and the holder is trusted with positions it reports, so a cheating holder can move the ball anywhere.
Queued for review
- Two crates stand 4 studs apart. The crawler keeps trying to squeeze between them and getting wedged. Which parameter should you raise?
- With ten crawlers, the server's frame time spikes. Which line is the problem?
- The crawler is in Attack, a player is 2 studs away, and a wrench hit stuns it this tick. Using the table, what state is it in next?
Open this step in lesson mode · Link to this step · This confused me