Skip to content

Navmesh Surface

Updated

The scene’s walkable navmesh that agents find paths on.

Type
ent-navmesh-surface
Script class
NavMeshSurfaceEntity

A NavMesh Surface owns the scene’s navmesh (navigation mesh): a simplified map of every place a character can stand, which characters use to find their own way around walls and through doors. The map is baked, that is computed once, from the surfaces you mark as walkable and the obstacles you mark as collidable. The surface keeps the result, so play loads it at once. It also runs the crowd: every character with a NavMesh Agent moves in it and avoids the others.

Put one NavMesh Surface in a scene that has characters who walk on their own. It has no position of its own, because the navmesh covers the geometry wherever it is. Only one surface is used across the active scenes.

  • In the editor, selecting the surface draws the navmesh over the scene, and the Bake action computes it.
  • In play, agents join the navmesh a few frames after play starts. Without baked data, play bakes the navmesh when it is first needed, which delays the characters.

The other navigation pieces are components and one sibling entity: NavMesh Walkable marks floors, NavMesh Collidable marks obstacles, a NavMesh Agent moves a character, and a NavMesh Link joins areas the surface does not otherwise connect, such as a gap to jump.

The bake settings that matter most:

  • agentRadius is the clearance kept from walls and edges, in metres. It is independent of the radius each NavMesh Agent has in play.
  • agentHeight is the headroom a character needs, in metres. Places under a lower ceiling are left out.
  • agentMaxClimb is the tallest step a character climbs, and agentMaxSlope the steepest walkable slope, in degrees.
  • cellSize and cellHeight set the resolution. Smaller cells follow edges more closely but take longer to bake.

The other settings tune how the outline is simplified; the table below lists them with their ranges.

  1. Add a NavMesh Surface entity to the scene. See Scenes and hierarchy.
  2. Add a NavMesh Walkable component to floors, ramps and platforms, and a NavMesh Collidable to walls, furniture and crates.
  3. Set agentRadius, agentHeight, agentMaxClimb and agentMaxSlope to match your characters.
  4. Select the surface to see the navmesh, and bake it. Bake again whenever you move walls, floors or links.
  5. Give each character a NavMesh Agent, usually with a Character Controller on the same entity.

Wait until the navmesh and crowd are live, then announce it once.

NavReady.jx
#pragma lifecycle(startup, update)
let surface;
let announced = false;
function startup() {
surface = findEntity('NavMesh Surface')?.getComponent(NavMeshSurfaceComponent);
}
function update() {
if (announced || !surface || !surface.isReady) return;
announced = true;
emit('nav/ready');
log('Navigation is ready');
}

How it works:

  • getComponent(NavMeshSurfaceComponent) reaches the surface’s component, which holds the navmesh and the queries.
  • isReady becomes true once the navmesh and its crowd are live, a few frames into play.
  • Scripts that move characters can start on on('nav/ready', …) instead of retrying every frame.

Scatter pickups where players can reach them

Section titled “Scatter pickups where players can reach them”

Place coins at random spots that are guaranteed to be on walkable ground.

ScatterCoins.jx
#pragma lifecycle(startup)
const COUNT = 10;
const AREA = 15; // metres around the centre
function startup() {
const surface = findEntity('NavMesh Surface').getComponent(NavMeshSurfaceComponent);
const centre = { x: 0, y: 0, z: 0 };
on('nav/ready', () => {
for (let i = 0; i < COUNT; i++) {
const spot = surface.randomPointAround(centre, AREA);
if (!spot) continue;
spawn('Coin', { position: { x: spot.x, y: spot.y + 0.5, z: spot.z }, enabled: true });
}
});
}

How it works:

  • The script waits for nav/ready, sent by the previous example, so the navmesh exists before it is queried.
  • randomPointAround(center, radius) returns a random reachable point within radius of center, or undefined when there is none.
  • spawn copies a disabled Coin template to each point, half a metre above the ground.

Before sending a character somewhere, check that a path exists and measure how long it is.

RouteCheck.jx
#pragma lifecycle(startup)
function pathLength(corners) {
let length = 0;
for (let i = 1; i < corners.length; i++) {
const a = corners[i - 1];
const b = corners[i];
length += Math.hypot(b.x - a.x, b.y - a.y, b.z - a.z);
}
return length;
}
function startup() {
const surface = findEntity('NavMesh Surface').getComponent(NavMeshSurfaceComponent);
const from = new THREE.Vector3();
const to = new THREE.Vector3();
on('route/check', (data) => {
findEntity(data.from)?.getWorldPosition(from);
findEntity(data.to)?.getWorldPosition(to);
const start = surface.closestPoint(from);
const goal = surface.closestPoint(to);
const corners = start && goal ? surface.computePath(start, goal) : [];
if (corners.length === 0) log('No route from', data.from, 'to', data.to);
else log('Route of', pathLength(corners).toFixed(1), 'm with', corners.length, 'corners');
});
}

How it works:

  • closestPoint snaps each position onto the navmesh, or returns undefined when nothing is near.
  • computePath(from, to) returns the corners of the path between two points; an empty list means the goal cannot be reached.
  • The length is the sum of the distances between corners. Emit route/check with { from: 'Guard', to: 'Treasure' } to try it.

Rebuild the navmesh after the level changes

Section titled “Rebuild the navmesh after the level changes”

Bake again at runtime when a script has built or changed the level.

RuntimeBake.jx
#pragma lifecycle(startup)
function startup() {
const surface = findEntity('NavMesh Surface').getComponent(NavMeshSurfaceComponent);
// Another script builds a maze, then emits 'maze/built'.
on('maze/built', async () => {
emit('hud/toast', { text: 'Preparing paths…' });
const ok = await surface.bake((progress) => log(`Baking ${Math.round(progress * 100)}%`));
emit(ok ? 'maze/ready' : 'maze/failed');
});
}

How it works:

  • bake(onProgress) computes a fresh navmesh from the current geometry and links, replaces the live one, and calls onProgress with how much is done, from 0 to 1.
  • It returns a promise of true on success, so the async listener can await it. It resolves false when there was nothing to bake, the surface is off, or the bake was stopped.
  • The bake works a little each frame, so the game keeps running while it does. cancel() stops a bake under way.
  • Bake in the editor before you publish. A scene without baked data bakes on load, and characters wait until it is done.
  • If characters walk through a wall, give the wall a NavMesh Collidable and bake again. If they refuse a floor, check that it has a NavMesh Walkable and is not steeper than agentMaxSlope.
  • If nothing is marked walkable or collidable, the bake uses every visible mesh, so a first bake still gives something. Mark your geometry for a clean result.

What a new Navmesh Surface is made of. Required components are always present and cannot be removed; the others can. Per entity says whether an entity can hold one of that component or several. Layer, Lock and Enable are on every placed entity, and Transform holds its position, rotation and scale.

Component Type Role Per entity What it does
Layer comp-layer Required One Puts the entity on a render/raycast layer so cameras and rays can include or skip it.
Lock comp-lock Required One Editor-only flag that stops the entity from being selected or moved.
Enable comp-enable Required One Turns the entity and its children on or off: hides them and stops their behavior.
Navmesh Surface comp-navmesh-surface Required One The scene’s walkable navmesh that agents find paths on.

You can also add 1 optional components, such as Signal Emitter.

The settings of a new entity, as the runtime creates it. Change them in the Properties panel of XR Creator, or from a script with getComponent(…).setProps({ … }).

Prop Default Range
cellSize 0.166 0.1 ≤ x ≤ 10
cellHeight 0.1 0.1 ≤ x ≤ 1
agentHeight 1.7 0.30000000000000004 ≤ x ≤ 10
agentRadius 0.5 0 ≤ x ≤ 5
agentMaxClimb 0.3 0 ≤ x ≤ 10
agentMaxSlope 45 0.1 ≤ x ≤ 89.999
regionMinSize 4 0 ≤ x ≤ 150
regionMergeSize 20 0 ≤ x ≤ 150
edgeMaxLen 12 0 ≤ x ≤ 50
edgeMaxError 1 0 ≤ x ≤ 3
vertsPerPoly 6 3 ≤ x ≤ 6
detailSampleDist 6 0 ≤ x ≤ 16
detailSampleMaxError 1 0 ≤ x ≤ 16

With a Signal Emitter on the entity, these events reach scripts as { entityId, eventType, data }. Compare eventType with the EventType constants.

It reports the events every entity has: Transform::change (and position-change, rotation-change, scale-change), Enable::change, Layer::change and Lock::change.

Run it in the browser, read its scripts, and download it as an XR Creator project.

Find the entity by its name, check its class, and work with its components. Name the entity in the Hierarchy first; this example expects My Navmesh Surface.

NavMeshSurfaceEntity.jx
#pragma lifecycle(startup)
function startup() {
// Find the entity by the name it has in the Hierarchy.
const entity = findEntity('My Navmesh Surface');
if (!(entity instanceof NavMeshSurfaceEntity)) return;
// Its Navmesh Surface component holds the settings listed under Props.
const component = entity.getComponent(NavMeshSurfaceComponent);
log('cellSize is', component.props.cellSize);
component.setProps({ cellSize: 0.25 });
}