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.

Project lesson, about 75 minutes, 12 steps

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.

Roblox Studio
Beacon Yard during a drill: the hovering drone close behind a player, with the drone's health bar above it and the HUD at the top left.

Select a numbered pin, or a row below, to read what it marks.

Figure 1.1.

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?

  1. The crawler walks into the crate and stays stuck against it
  2. It walks through the crate, like the drone
  3. It jumps over automatically
  4. It picks a different player
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 parameterWhat it meansDefault
AgentRadiusHow much room the agent needs from obstacles, in studs2
AgentHeightGaps lower than this are not walkable5
AgentCanJumpWhether the path may include jumpstrue
AgentCanClimbWhether it may climb TrussPartsfalse
WaypointSpacingDistance between intermediate waypoints4
CostsHow much to avoid materials or labelled regionsnone
luau
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?

  1. AgentRadius
  2. AgentHeight
  3. WaypointSpacing
  4. AgentCanJump
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.

luau
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)
Figure 3.1
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.

  1. Walk toward the next waypoint (Move or MoveTo) until it is reached
  2. CreatePath with the crawler's agent parameters (once)
  3. Repeat until the last waypoint, or re-path if something changed
  4. ComputeAsync from the crawler's root to the target
  5. Check that Status is Success and read GetWaypoints
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

The pathfinding grid: a still of the simulation
Figure 4.1.

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?

  1. It goes around both crates, because the gap is now too narrow
  2. It still uses the gap
  3. No path is found anywhere
  4. The crates move apart
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.Blocked fires 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.
Luau
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)
Figure 5.1. Expected output: re-path at 0.6 re-path at 0.8 re-path at 2.1 paths 3

With 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, and math.huge makes one unwalkable.
  • PathfindingModifier. Put one inside an invisible, anchored, non-colliding part and give it a Label, such as Hazard. Add Hazard = 10 to Costs and the whole region becomes expensive, whatever it is made of. With PassThrough on, 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 a Label your 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.

StateBecomesWhen
anyStunnedA wrench hit lands
StunnedIdleThe stun time has passed
Idle or ChaseAttackA living player is within 4 studs
IdleChaseA living player is within 40 studs and a path exists
ChaseIdleThe 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
  1. Stunned
  2. Attack
  3. Chase
  4. Idle
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.

Both sidesNetwork ownership is whoever holds the ball.
In the pictureIn Roblox
Holding the ballSimulating an assembly's physics
Passing to the nearest playerThe engine's automatic ownership near a character
The referee taking the ball backSetNetworkOwner(nil) on the server

See the whole analogy cast

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?

  1. One loop that updates every crawler, instead of one script per crawler
  2. SetNetworkOwner(nil) on each crawler's root
  3. Re-path on Blocked or when the target moves 6 studs, at most every 0.5 seconds
  4. Compute a new path for every crawler on every Heartbeat
  5. Let each client run the crawlers near it to save server time
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

OptionWhat it isWhen pros pick itTrade-offs
PathfindingServiceRoblox'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 onlyMove 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 modulesOpen-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

m07-feel to m08-crawler

  • src/server/CrawlerService.luau
  • src/server/CrawlerBrain.luau
  • src/server/MapBuilder.luau
  • src/server/init.server.luau
  • src/shared/Config.luau
  1. Check out m08-crawler, run rojo 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.

  2. Inspect git diff --stat m07-feel m08-crawler -- src and open src/server/init.server.luau, src/server/CrawlerBrain.luau and src/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.

  3. Start a drill and watch the crawler spawn from the south-west corner with SetNetworkOwner(nil) on its root and follow waypoints from CrawlerBrain.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.

  4. Lead the crawler around the scrap stacks and watch CrawlerBrain.shouldRepath and path.Blocked trigger 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?

  1. Cancelling the walk in progress (humanoid:Move(Vector3.zero), or MoveTo(root.Position) if using MoveTo)
  2. Re-computing the path
  3. Setting the network owner
  4. Resetting the damage cooldown
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 1, Apprentice

Challenge

Turn on the navigation mesh in Beacon Yard and find where a default-size agent cannot walk.

Start from
The game at milestone m08 (download)

Done means

  • You can show where an agent can and cannot walk in the yard
  • You can point to the gap the pedestal, scrap stacks and shop leave in the navigation mesh

Hints

  1. Visualization Options is the icon at the top right of the viewport during Play.
  2. Turn on Navigation mesh.

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

  1. m08-crawler ships the Neon Hazard stripe without a PathfindingModifier; add an invisible, anchored, CanCollide = false part over it with a PathfindingModifier labelled Hazard.
  2. 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?

  1. A PathfindingModifier with PassThrough on, in a part around the gate
  2. Costs = { DiamondPlate = math.huge }
  3. AgentCanJump = true
  4. A larger AgentRadius
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

  1. Check the strongest condition first: stunned beats everything.
  2. A failed path means give up and go Idle.
  3. 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

  1. 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.
  2. 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.
  3. 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.

Next Physics: constraints, assemblies, network ownership

Open this step in lesson mode · Link to this step · This confused me