GameCrew AIEarly access
Sign in
Three.jsaiCompile-verified pattern

Zero-Allocation Context Steering, Patrol Loops & Telegraphed AI in Three.js

Deterministic 60 Hz enemy and companion AI in Three.js using 8-slot context steering against CollisionWorld, level.json patrol loops, attack-token pacing, and telegraphed strikes.

  • ai
  • enemy
  • npc
  • steering
  • patrol
  • telegraph
  • combat
  • attack-tokens
  • threejs

When to Use & Field Best Practices

In 60 Hz browser games (game.onUpdate), enemy and NPC AI must be readable to the player, deterministic, and zero-allocation per step so headless play tests and 90 Hz headsets never stutter:

  1. 8-Slot Context Steering on CollisionWorld: Pre-allocate 8 unit horizontal directions and scratch THREE.Vector3 instances; probe world.raycast along each slot to mask walls/pillars while steering smoothly around corners or orbiting the player.
  2. Explicit telegraph -> strike -> recover Phases: Flash an emissive windup color and play an audio cue (game.audio.play('telegraph')) for 0.45 s before the strike window opens, then hold recover (0.65 s) so skilled players can punish dodged attacks.
  3. Encounter Attack Tokens: Share an AttackTokenPool(2) across the encounter so at most 2 enemies lunge simultaneously while others circle on a strafe ring.

Mathematical & Algorithmic Core

  • Context Slot Score: For 8 unit directions u_i = (cos (π i)/(4), 0, sin (π i)/(4)), interest I_i = max(0.05, u_i · g), obstacle danger D_i = clamp(1 - d_i / R_probe, 0, 1), and unblocked weight S_i = I_i (1 - D_i) when D_i ≤ 0.7.
  • Tangential Strafe Orbit: g_orbit = normalize(r · clamp(fracd - r_prefr_pref, -1, 1) + 0.75 t).

Engine Implementation

Zero-GC Context Steering + Token Pool + Enemy Brain (Assets/Game/enemyAi.ts)

import * as THREE from 'three';
import type { CollisionWorld, Game } from 'ccgd';

export type EnemyPhase = 'patrol' | 'strafe' | 'telegraph' | 'strike' | 'recover';

const DIRS: readonly THREE.Vector3[] = Array.from({ length: 8 }, (_, i) => {
  const a = (i * Math.PI) / 4;
  return new THREE.Vector3(Math.cos(a), 0, Math.sin(a));
});

const _origin = new THREE.Vector3();
const _goal = new THREE.Vector3();
const _sum = new THREE.Vector3();

export class AttackTokenPool {
  private readonly holders = new Set<string>();
  maxTokens: number;

  constructor(maxTokens = 2) {
    this.maxTokens = maxTokens;
  }

  tryAcquire(id: string): boolean {
    if (this.holders.has(id)) return true;
    if (this.holders.size >= this.maxTokens) return false;
    this.holders.add(id);
    return true;
  }

  release(id: string): void {
    this.holders.delete(id);
  }

  get activeCount(): number {
    return this.holders.size;
  }
}

export function solveContextSteering(
  world: CollisionWorld,
  position: THREE.Vector3,
  desiredDir: THREE.Vector3,
  probeDist = 2.2,
  out = new THREE.Vector3()
): THREE.Vector3 {
  _goal.set(desiredDir.x, 0, desiredDir.z);
  if (_goal.lengthSq() < 1e-6) return out.set(0, 0, 0);
  _goal.normalize();

  _origin.set(position.x, position.y + 0.6, position.z);
  _sum.set(0, 0, 0);
  let total = 0;

  for (let i = 0; i < 8; i++) {
    const u = DIRS[i];
    const interest = Math.max(0.05, u.dot(_goal));
    const hit = world.raycast(_origin, u, probeDist);
    const danger = hit ? Math.max(0, Math.min(1, 1 - hit.distance / Math.max(0.05, probeDist))) : 0;
    if (danger > 0.7) continue;
    const score = interest * (1 - danger);
    _sum.addScaledVector(u, score);
    total += score;
  }

  return total > 1e-4 ? out.copy(_sum).normalize() : out.copy(_goal);
}

export function orbitDirection(
  selfPos: THREE.Vector3,
  targetPos: THREE.Vector3,
  preferredRadius = 4.2,
  orbitSign: 1 | -1 = 1,
  out = new THREE.Vector3()
): THREE.Vector3 {
  const dx = targetPos.x - selfPos.x;
  const dz = targetPos.z - selfPos.z;
  const dist = Math.hypot(dx, dz);
  if (dist < 1e-4) return out.set(0, 0, 1);
  const rx = dx / dist;
  const rz = dz / dist;
  const tx = -rz * orbitSign;
  const tz = rx * orbitSign;
  const rw = Math.max(-1, Math.min(1, (dist - preferredRadius) / Math.max(0.5, preferredRadius)));
  return out.set(rx * rw + tx * 0.75, 0, rz * rw + tz * 0.75).normalize();
}

export class EnemyBrain {
  readonly id: string;
  readonly waypoints: THREE.Vector3[];
  private readonly pool?: AttackTokenPool;
  phase: EnemyPhase = 'patrol';
  waypointIndex = 0;
  timer = 0;
  memorySec = 0;
  readonly lastSeen = new THREE.Vector3();
  private readonly steer = new THREE.Vector3();
  private readonly desired = new THREE.Vector3();

  constructor(id: string, waypoints: THREE.Vector3[] = [], pool?: AttackTokenPool) {
    this.id = id;
    this.waypoints = waypoints;
    this.pool = pool;
  }

  step(
    game: Game,
    world: CollisionWorld,
    selfPos: THREE.Vector3,
    forward: THREE.Vector3,
    targetPos: THREE.Vector3,
    dt: number,
    outMove = new THREE.Vector3()
  ): THREE.Vector3 {
    const sightRange = game.tuning.value('enemySightRange', 14);
    const telegraphSec = game.tuning.value('enemyTelegraphSec', 0.45);
    const recoverSec = game.tuning.value('enemyRecoverSec', 0.65);

    const dx = targetPos.x - selfPos.x;
    const dz = targetPos.z - selfPos.z;
    const dist = Math.hypot(dx, dz);
    const inCone =
      dist <= sightRange && (dist < 1e-3 || (forward.x * dx + forward.z * dz) / dist >= 0.35);
    const eye = _origin.set(selfPos.x, selfPos.y + 1.1, selfPos.z);
    const rayDir = this.desired.set(dx, 0, dz).normalize();
    const blocked = dist > 0.4 && world.raycast(eye, rayDir, dist - 0.35) !== null;
    const sees = inCone && !blocked;

    if (sees) {
      this.lastSeen.copy(targetPos);
      this.memorySec = 2.5;
    } else if (this.memorySec > 0) {
      this.memorySec = Math.max(0, this.memorySec - dt);
    }

    switch (this.phase) {
      case 'patrol': {
        if (sees) {
          this.phase = 'strafe';
          return outMove.set(0, 0, 0);
        }
        if (this.waypoints.length === 0) return outMove.set(0, 0, 0);
        const wp = this.waypoints[this.waypointIndex % this.waypoints.length];
        if (Math.hypot(wp.x - selfPos.x, wp.z - selfPos.z) < 0.65) {
          this.waypointIndex = (this.waypointIndex + 1) % this.waypoints.length;
        }
        this.desired.subVectors(wp, selfPos);
        return solveContextSteering(world, selfPos, this.desired, 2.2, outMove).multiplyScalar(0.65);
      }
      case 'strafe': {
        if (!sees && this.memorySec <= 0) {
          this.pool?.release(this.id);
          this.phase = 'patrol';
          return outMove.set(0, 0, 0);
        }
        if (sees && dist <= 3.5 && (!this.pool || this.pool.tryAcquire(this.id))) {
          this.phase = 'telegraph';
          this.timer = telegraphSec;
          return outMove.set(0, 0, 0);
        }
        const goal = sees ? targetPos : this.lastSeen;
        orbitDirection(selfPos, goal, 4.2, this.id.charCodeAt(0) % 2 === 0 ? 1 : -1, this.steer);
        return solveContextSteering(world, selfPos, this.steer, 2.2, outMove);
      }
      case 'telegraph': {
        this.timer -= dt;
        if (this.timer <= 0) {
          this.phase = 'strike';
          this.timer = 0.22;
        }
        return outMove.set(0, 0, 0);
      }
      case 'strike': {
        this.timer -= dt;
        if (this.timer <= 0) {
          this.pool?.release(this.id);
          this.phase = 'recover';
          this.timer = recoverSec;
        }
        return outMove.set(forward.x, 0, forward.z).normalize().multiplyScalar(1.65);
      }
      case 'recover': {
        this.timer -= dt;
        if (this.timer <= 0) this.phase = sees ? 'strafe' : 'patrol';
        return outMove.set(0, 0, 0);
      }
    }
  }
}

Performance & Determinism Traps

  • Zero allocations in game.onUpdate: Reuse module-level scratch vectors (_origin, _goal, _sum) and instance vectors (this.steer, this.desired) so 1,000 fast-forwarded test steps allocate zero garbage.
  • Strip-only TypeScript (erasableSyntaxOnly): Declare class fields explicitly instead of using constructor parameter properties (constructor(public ...)).

Verification Checklist

  1. Add a play test in Assets/Game/Tests/play/ stepping EnemyBrain through patrol -> strafe -> telegraph -> strike -> recover and asserting AttackTokenPool.activeCount <= 2.
  2. Run compile, test_play, and audit_game to confirm clean TypeScript types and bounded tuning.json knobs.

Official references

  • Andrew Fray (Game AI Pro 2, Ch. 18 — Context Steering)
  • Craig Reynolds (GDC 1999 — Steering Behaviors)
  • DOOM 2016 Encounter Token Architecture (GDC 2017)

Playable Three.js games made with GameCrew

Launch a real browser build using this engine and inspect its controls or fork its project tree.

More Three.js techniques

optimization

Instanced Wind Foliage, Object-Pooled Particles & Spring Feel in Three.js →

Single-draw-call THREE.InstancedMesh wind foliage with player bend, zero-GC pooled burst particles, and dt-invariant second-order springs that keep 60 Hz steps under 2 ms.

atmosphere

Raymarched Volumetric Clouds & Atmospheric Sky Shaders in Three.js (WebGL 2) →

Self-contained THREE.ShaderMaterial sky dome in GLSL ES 3.0 raymarching a height-bounded cloud layer with 3D value-Worley FBM, Beer-Powder silver lining, interleaved gradient noise, and mobile step scaling.

physics

BVH Mesh & Character Capsule Collision in Three.js →

Fast capsule-vs-triangle pushout and slope resolution using three-mesh-bvh shapecasts, pre-allocated scratch vectors, and CollisionWorld.

gameplay

Multiplayer Room State Sync & 60 Hz Avatars in Three.js →

Solo-first multiplayer with smooth 60 Hz remote avatars, host-owned shared state, reliable host claims, and deterministic two-peer room tests.

Use verified techniques inside a real game

Describe your game idea for free or connect an MCP assistant to search and contribute techniques.

Learn about collaboration