logo

Babylon.js Market

AiPilot

ai

AiPilot

1
Unlock

Install with the CLI:

bjs download AiPilot

AiPilot

The enemy brain for a 6-DOF space dogfight — a hostile ship that circles its target, banks into every turn, and opens fire the instant its nose lines up.

What it does

AiPilotComponent is pure orbit state: a circular orbitRadius around the target, a vertical orbitHeight offset, a live orbitAngle phase, and an angularVel whose sign picks CW vs CCW so a fleet spreads across separate arcs instead of stacking on one. targetTag chooses whom to hunt — 'player' or 'freighter'.

AiPilotSystem (query: AiPilot + FlightIntent + Transform6DOF, priority 90) does the flying, once per frame per pilot. It advances orbitAngle by angularVel · dt, then aims not at the ship's current orbit spot but at a lookahead point ~1.8s further around the orbit, centred on the target's current pose — so the orbit chases the target as it moves and the ship banks into the turn instead of trailing it. When the target drifts inside gun range it blends the steering point off the orbit tangent and onto the target (a linear ramp: 0 at gun.range, fully aimed at gun.range · 0.5 or closer), because on a pure tangent the nose points ~90° off the target and the fire gate never opens. The ship breaks orbit to line up the shot, then resumes circling once the target slides back out.

The ship→point direction becomes a desired yaw and pitch; the error is pushed into FlightIntent at P-gain 2.0, roll is coupled to yaw so the AI banks into the turn (-(yawErr + avoidYaw·0.4)·1.4), and throttle holds 0.42, easing off while it's actively dodging. Fire control opens gun.isFiring only when the target sits inside the AI's forward ±20° cone and within gun.range (and more than 1 unit away). Running at priority 90, ahead of FlightControl (80) and MachineGun (77), it writes FlightIntent and gun.isFiring for those two to consume the same frame. It also adds a perpendicular avoidance nudge toward the most-threatening rock in its forward cone — a no-op until the scene has asteroid-tagged obstacles.

Use it in a scene

A scene is just data — a list of entities, each with its components. At startup the SceneLoader turns this JSON into a live world; edit the file and reload to rebuild it.

Build it from scratch with the bjs CLI:

  1. 1Scaffold a project
    npm create @babylonjsmarket/arcade@latest my-game

    World, renderer, and dev server — ready to run.

  2. 2Install dependencies
    cd my-game && npm install
  3. 3Add AiPilot
    bjs download AiPilot

    Copies its source into src/ so the scene resolves.

    First time? Run bjs login once.

  4. 4Paste the scene into src/scenes/arcade-room.ts and run
    npm run dev

    SceneLoader builds the world from the JSON; reload to rebuild.

JSON
{
  "Enemy1": {
    "tags": ["enemy"],
    "components": {
      "Transform6DOF": { "x": 180, "y": 0, "z": -60 },
      "AiPilot": { "orbitRadius": 220, "orbitHeight": 20, "angularVel": 0.25, "targetTag": "player" },
      "FlightIntent": {},
      "MachineGun": {}
    }
  }
}

Props

  • orbitRadius (number, default 200) — radius of the circular orbit the pilot flies around its target.
  • orbitHeight (number, default 0) — vertical offset of the orbit plane above (or below) the target.
  • orbitAngle (number, default 0) — current orbit phase in radians; advanced every frame by angularVel · dt. Serialized so save/load round-trips the fleet's formation.
  • angularVel (number, default 0.2) — orbit speed in radians per second; the sign flips CW vs CCW, so seeding a fleet with mixed signs fans it out onto separate arcs.
  • targetTag ('player' | 'freighter', default 'player') — which entity this pilot orbits and shoots. A 'freighter' pilot falls back to the player if the freighter is gone.

Events

  • Emits nothing and listens for nothing — the component declares no events constant, and the System never touches the bus. It steers by writing its neighbours directly: FlightIntent (yaw, pitch, roll, throttle, boost) and, when armed, MachineGunComponent.isFiring. FlightControl and MachineGun read those the same frame.
  • Targets are found by tag, not by the bus: the player via world.getEntitiesByTag('player'), the optional escort via 'freighter-head' (the head only — trailing cars share the freighter tag but are not orbited), and obstacles via 'asteroid'.

Dependencies

  • Transform6DOF — every pilot needs one; its position + quaternion give the ship's pose and body axes (forward/right/up) for steering, the ±20° fire test, and avoidance.
  • FlightIntent — the stick the AI drives. The System writes yaw/pitch/roll/throttle/boost here exactly as a human pilot would, and FlightControl turns intent into motion downstream.
  • MachineGun — read optionally (entity.get(MachineGunComponent)): an armed pilot gets range-gated fire control and the aim-into-range steering blend; an unarmed one still flies the orbit. The gun's range also sets the inner ring where the steering blend fully aims at the target.

Notes

  • A player-tagged entity must exist, carrying a Transform6DOF. With no player tag in the scene, AiPilotSystem early-returns and every pilot sits inert. This is the #1 gotcha.
  • Fire needs a MachineGun. Without one the ±20° gate is skipped entirely — the ship orbits and lines up shots it can't take. Give the pilot a MachineGun to make it dangerous; its range also controls how tightly the nose swings onto the target inside range.
  • Sign of angularVel spreads the fleet. Same radius + opposite signs put two pilots on counter-rotating arcs; identical signs stack them. Vary radius/height/sign when spawning a wing so they don't fly as one dot.
  • Freighter pilots self-heal. A targetTag: 'freighter' pilot orbits the freighter-head, then falls back to hunting the player the moment that head is destroyed — the wing stays engaged instead of circling an empty waypoint.
  • Obstacle avoidance is opt-in by tag. The perpendicular dodge only fires for active entities tagged asteroid that expose numeric hx/hy/hz half-extents; the math is dormant (and free) in a scene with no rocks.

More like this

FlightIntent
MachineGun
Transform6DOF
AIGoalSeek
AIKick
AIZone
Animation
ArcCamera
Asteroid
BallPossession
BallPursuit
Bullet
CameraFollow
DirectionalLight
Enemy
EnemySpawner
EnvironmentTexture
FreighterCar
FreighterChain
FreighterHead
GameConfig
Health
HemisphericLight
Jump
KeyboardInput
KeyboardMover
Lifetime
LineOfSight
Mesh
MeshPrimitive
Missile
MissileLauncher
MissionDirector
Movement
Obstacle
ObstacleField
OilBlob
Parts
Physics
PlayerInput
PlayerWalkAnimator
PokerAI
PokerAIBill
PokerAICali
PokerAIRandy
PokerAIShark
PokerAISurge
PokerAITilt
RespawnTimer
Score
Shadow
ShipLoadout
SkeletonAnimator
SpaceShooterBullet
SpaceShooterHealth
SpaceShooterScore
WaveDirector
Waypoint
WaypointTrack

Was this page helpful?

We read every note — tell us what's working and what isn't.

↑↓ NavigateEnter SelectEsc CloseCtrl+K Open Search