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

Step 1 of 12

Flying 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.

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.

Choose one

Suppose the crawler copied the drone's movement: each frame, step straight toward the nearest player. A crate stands between them. What happens?

Suppose the crawler copied the drone's movement: each frame, step straight toward the nearest player. A crate stands between them. What happens?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 2 of 12

Ask 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.

Choose one

Two crates stand 4 studs apart. The crawler keeps trying to squeeze between them and getting wedged. Which parameter should you raise?

Two crates stand 4 studs apart. The crawler keeps trying to squeeze between them and getting wedged. Which parameter should you raise?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 3 of 12

Walk 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)
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 in order

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

Link to this step · This confused me

Step 4 of 12

See 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

Goal Drop a crate on the crawler's path while it walks, and watch it re-path around the crate without walking back to the start.

The pathfinding grid: a preview of the simulation

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.

Choose one

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?

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?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 5 of 12

Blocked 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
Ctrl Enter runs the cell. Checked against the expected output
Find the broken line

With ten crawlers, the server's frame time spikes. Which line is the problem?

With ten crawlers, the server's frame time spikes. Which line is the problem?

Press 1 to 5 to choose, Enter to check.

Link to this step · This confused me

Step 6 of 12

Costs, 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.

Work it out

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?

Link to this step · This confused me

Step 7 of 12

A 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.

Predict the output

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
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?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 8 of 12

Keep 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.

Choose all that apply

Which choices keep ten crawlers cheap and fair on the server?

Which choices keep ten crawlers cheap and fair on the server?

Press 1 to 5 to choose, Enter to check.

Link to this step · This confused me

Step 9 of 12

Build 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.

Link to this step · This confused me

Step 10 of 12

Where 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.

Choose one

A bug report says a stunned crawler slides another few studs before stopping. Which side effect is missing on entering Stunned?

A bug report says a stunned crawler slides another few studs before stopping. Which side effect is missing on entering Stunned?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 11 of 12

Challenges

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

Meet the criteria above, then record your own result. No test grades this check.

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

Meet the criteria above, then record your own result. No test grades this check.

Choose one

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?

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?

Press 1 to 4 to choose, Enter to check.

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

The Course Runner prints this code when the test passes.

Link to this step · This confused me

Step 12 of 12

Recap

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

Link to this step · This confused me