FERRETGame engine over Babylon.js
Ferret

AI and navigation

Skill ferret-ai-navigation · download all skills · SKILL.md

When to use#

Walking NPCs, following the player, stopping to talk, behaviour trees.

The model#

NavService builds or loads a NavMesh (recast-navigation as WebAssembly, loaded once by initNavigation) and answers path and point queries. NavAgent moves an entity over it in the crowd. Ready behaviours: Roam (random points near home), Follow, Attention (stop and face a player who comes near). BehaviorTree (bt, BTNode, Blackboard) is there for more.

Steps#

  1. await initNavigation() once, then create NavService with the level's geometry (collectGeometry) or navmesh.bin.
  2. Give the level's manifest a navmesh file or navBuild settings; rebuild with the editor command edit.navmesh.rebuild after geometry changes.
  3. Add NavAgent plus a behaviour to the entity (by name in the manifest).
  4. Over a ledge or an explosion impulse the agent switches to a falling mode and lands back on the mesh.

Postures of people who wait (posture.ts)#

A crowd that is not going anywhere must not stand in rows like posts. newPosture(seed, posture) gives each person a state; stepPosture(state, dt, activity) each step, with activity one of wait (on a beach: sit, crouch, lie, talk, stand), queue (on his feet, a word, a crouch), cover (down), walk (up), aboard (packed on a deck: sit, stand, crouch, no lying). It returns canWalk (a walking order waits for it; call standUp first) and wantsStep (a few steps about the spot are natural now). Changes take seconds (POSTURE_DOWN: sit 2.6 s, lie 3.8 s, crouch 1.6 s); poseOf(state) gives the posture to draw and how far into it (0 standing, 1 down), going up through standing between two low postures. Draw it by cross-fading clips by that amount (clipFor maps postures to the Character Customizer clips: Idle*, Talking_*, Pose_Sitting_Male, M_Neutral_Crouch_Idle_Loop, the end of Death_Backward) or by blending a vertex pose. Pure numbers and seeded: the same crowd waits the same way on every peer. Import it by its file (packages/ai/src/posture) where the NavMesh WebAssembly is not wanted.

Check afterwards#

A path query between two spawn points is non-empty; agents reach targets headless in a few simulated seconds; Attention stops an NPC when the player is near.

What usually goes wrong#

  • People snap from standing to sitting in one frame: the pose is drawn from posture instead of poseOf(...).amount, or the clips are switched instead of cross-faded by it.
  • No NavMesh: navmesh.bin missing and no navBuild.
  • Agent radius or height in navBuild too big for doorways.
  • Calling queries before initNavigation finished.
  • Terrain that changes (digging): the mesh must follow, see ferret-physics-terrain.

Files#