Web Games From Zero · Episode 06

Enemies & AI

Enemies & AI is Episode 06 of Web Games From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 06 · Web Games From Zero

A game needs an opponent. Up to now we've had a player who can move, jump, collide, and feel good doing it — but nothing to do it against. The moment you add a single thing that notices you and gives chase, an empty playground becomes a game. Today we build that thing: enemies that patrol a beat, snap to attention when you wander too close, hunt you down, and back off when you slip away — then we stack them into escalating waves that get meaner the longer you survive.

None of this needs a neural network or a pathfinding library. The workhorse of game AI is a finite-state machine — a handful of named states and the rules for moving between them — plus a pinch of steering so a crowd of enemies flows toward you instead of fusing into one fat blob. It's a few dozen lines of code, it's completely readable, and every knob is yours to tune. Watch the demo below: it's playing itself in attract mode, so the enemies always have someone to chase. Press any key or click to take the controls.

0 fps
▶ playing demo — press any key / click to take over
move: WASD / arrows · chase the wave down
WAVE 1
One enemy walking a beat between two posts. No brain yet — just a path.

Six stages, one enemy "brain" growing a feature at a time. The stage <select> swaps which behaviors are switched on; the sliders re-tune the live system; the attract toggle hands the player back to the demo-AI so you can watch the enemies work from the outside.

What you're looking at

The blue triangle is the player — driven by you, or by a demo-AI that orbits and juke-steps so there's always a target on the field. The colored dots are enemies. Each one carries a state label floating above it (from Stage 2 on): PATROL, CHASE, ATTACK, or IDLE. The faint ring that appears around the player in the chase stages is the aggro range — cross it and nearby enemies wake up and come for you. The WAVE badge counts the escalating waves; in the final stage a health bar rides above the player and enemies chip it down on contact, knocking you back when they land a hit.

Every enemy runs the same update function every fixed step, and every enemy — like the player — gets its movement intent from one place. That uniformity is the whole trick: once the state machine and the steering are written once, "more enemies" is just a bigger array.

Stage 1 — A patrolling enemy

The simplest convincing enemy doesn't think at all: it walks a beat. Give it two (or more) waypoints and have it march from one to the next, flipping direction when it arrives. That's it — and it already reads as "a guard on duty," because purposeful movement along a fixed path is exactly what a bored sentry looks like. We seek the current waypoint, and when we're within a small radius of it, advance the index (wrapping around the loop).

Patrol is the fallback behavior — the thing an enemy does when nothing more interesting is happening. Keep that in mind; in two stages it becomes one branch of a bigger decision.

Stage 2 — The FSM

Now we give the enemy a tiny brain. A finite-state machine is two things: a state field naming what the enemy is doing right now, and a switch that, each step, runs that state's behavior and checks whether to transition somewhere else. Our four states:

StateWhat it doesLeaves when…
IDLEStands still, scanning. A brief rest at a post.idle timer elapses → PATROL
PATROLWalks the waypoint beat.player within aggro → CHASE; reaches post → IDLE
CHASESeeks the player at speed.player closer than attack range → ATTACK; player past leave range → PATROL
ATTACKLunges / strikes; deals contact damage.player steps back out of attack range → CHASE

In this stage there's no player pressure yet (aggro is effectively off), so you'll see enemies cycle IDLE → PATROL → IDLE — resting at a post, walking to the next, resting again. The label above each one shows the live state so the machine is never a mystery. The point of this stage is to see the states exist before we wire the interesting transitions.

Stage 3 — Chase (with hysteresis)

Here's where it comes alive. Turn the player into bait: when they enter an enemy's aggro range, PATROL flips to CHASE and the enemy seeks them — accelerates toward their position every step. Leave the range and it gives up and goes back to patrolling. Drag the aggro slider and watch the ring grow: a bigger ring means enemies notice you from farther away.

The subtlety — and the reason this stage exists separately — is hysteresis. If "start chasing" and "stop chasing" used the same distance, an enemy hovering right at the boundary would flip CHASE / PATROL / CHASE / PATROL many times a second: a jittery, twitching mess we call state thrash. The fix is two different thresholds: wake up at a near distance, but don't give up until the player is noticeably farther away. Enter tight, leave loose. The gap between them is a buffer that kills the flicker.

Stage 4 — A crowd + a spawner

One enemy is a tech demo; a crowd is a game. Crank the enemies slider and a spawner tops the field up to that count, easing new enemies in from the edges. But naive seek has an ugly failure mode: if every enemy steers at the exact same target, they all converge on the same pixel and merge into a single throbbing blob. It looks broken because it is broken.

The cure is separation steering. Before an enemy commits to its move, it looks at its close neighbors and adds a gentle push away from each one — summed up, the crowd self-spaces. Combine "seek the player" with "avoid your buddies" and you get a flock that pours toward you while keeping its elbows out. This is the cheapest, highest-impact piece of AI you can add: two nested loops and the swarm suddenly looks deliberate.

Stage 5 — Escalating waves

A flat stream of identical enemies gets boring fast. Waves give the game a pulse: clear the current batch and a short breather ticks down, then the next wave arrives — more enemies, moving faster, with a little more aggression. The WAVE badge counts up; between waves it shows the countdown so the player gets a beat to breathe before the next push.

The wave manager is just a few numbers: a wave index, a target count that scales with it, a speed multiplier that creeps up, and a timer for the gap. The spawner reads those numbers; everything else — the FSM, the steering — is unchanged. Difficulty becomes a couple of formulas you can tune to taste.

Stage 6 — A small fight

Finally, stakes. The player (or demo-AI) gets health, and enemies in ATTACK range deal contact damage — with a satisfying knockback that shoves the player away on each hit so you're not instantly chewed to death by a pile-up. Survive a wave and the next rolls in; take too many hits and the player blinks, recovers, and the fight resets. It's a complete (if tiny) combat loop — patrol, notice, chase, attack, damage, repeat — built entirely from the parts in the stages above.

How the code works

Everything runs on the series' fixed-timestep loop so the AI behaves identically at 30, 60, or 144 Hz — enemy speeds are "pixels per fixed step," never multiplied by a variable dt. Let's walk the four pieces that make the demo tick.

(a) The finite-state machine

The heart of it. Each enemy owns a state string and an stateTime timer. One function, called every fixed step, runs the current state's movement and evaluates its transitions. Note the two ranges, aggro (enter) and leave (exit) — leave is bigger, and that gap is the hysteresis that stops boundary thrash.

// One step of the brain for a single enemy.
function stepFSM(e, player, dist) {
  e.stateTime += STEP;
  const aggro = e.aggro;          // enter-chase radius (tight)
  const leave = e.aggro * 1.6;    // give-up radius (loose) → hysteresis
  const atk   = 26;               // contact / strike radius

  switch (e.state) {
    case 'IDLE':
      // stand still, then resume the beat
      if (dist < aggro) setState(e, 'CHASE');
      else if (e.stateTime > e.idleFor) setState(e, 'PATROL');
      break;

    case 'PATROL':
      patrol(e);                                // seek current waypoint
      if (dist < aggro) setState(e, 'CHASE');
      break;

    case 'CHASE':
      seek(e, player.x, player.y, e.speed);     // accelerate toward player
      if (dist < atk)        setState(e, 'ATTACK');
      else if (dist > leave) setState(e, 'PATROL');  // note: leave, not aggro
      break;

    case 'ATTACK':
      seek(e, player.x, player.y, e.speed * 0.6);
      if (dist > atk * 1.4) setState(e, 'CHASE');
      break;
  }
}
function setState(e, s) { e.state = s; e.stateTime = 0; }  // reset timer on enter

That's the whole pattern. Adding a new behavior later (flee, search, ranged) is just a new case plus the transitions that lead in and out of it — the structure never gets more complicated than this.

(b) Seek + separation steering

Two forces. Seek nudges velocity toward a target; we steer (blend toward the desired direction) rather than teleporting the velocity, which gives a natural bit of turn-radius. Separation sums an away-vector from every neighbor closer than some radius, weighted so closer buddies push harder. Apply seek for intent, then separation so they don't stack.

// Steer this enemy's velocity toward (tx,ty).
function seek(e, tx, ty, speed) {
  let dx = tx - e.x, dy = ty - e.y;
  const d = Math.hypot(dx, dy) || 1;
  const desx = (dx / d) * speed, desy = (dy / d) * speed;  // desired velocity
  e.vx += (desx - e.vx) * 0.12;   // blend, don't snap → smooth turns
  e.vy += (desy - e.vy) * 0.12;
}

// Push away from close neighbors so the crowd self-spaces.
function separation(e, others, radius) {
  let ax = 0, ay = 0;
  for (const o of others) {
    if (o === e) continue;
    const dx = e.x - o.x, dy = e.y - o.y;
    const d2 = dx*dx + dy*dy;
    if (d2 > 0 && d2 < radius*radius) {
      const d = Math.sqrt(d2);
      ax += (dx / d) * (1 - d / radius);   // closer → stronger push
      ay += (dy / d) * (1 - d / radius);
    }
  }
  e.vx += ax * 0.9;   // fold the away-sum into velocity
  e.vy += ay * 0.9;
}

(c) The spawner + wave manager

The wave manager holds the difficulty state; the spawner keeps the field populated up to the wave's target count, capping the active array so a runaway spawn can never flood the game. Count and speed both scale with the wave index.

const wave = { n: 1, breather: 0 };
const CAP = 60;                              // hard ceiling on active enemies

function waveTarget(n) { return Math.min(CAP, 3 + n * 2); }  // more each wave
function waveSpeed(n)  { return 0.9 + n * 0.12; }              // faster each wave

function stepWaves(enemies) {
  if (wave.breather > 0) {                 // between-wave pause
    wave.breather -= STEP;
    if (wave.breather <= 0) wave.n++;     // breather over → next wave
    return;
  }
  const target = waveTarget(wave.n);
  if (enemies.length < target && enemies.length < CAP) {
    enemies.push(spawnEnemy(waveSpeed(wave.n)));     // top up from the edges
  } else if (enemies.length === 0) {
    wave.breather = 2.5;                    // wave cleared → breathe, then escalate
  }
}

The CAP appears twice on purpose: it bounds waveTarget and guards the spawn call, so no formula or off-by-one can ever push past the ceiling. That's your insurance against a spawn flood tanking the frame rate.

(d) Contact damage + knockback

When an enemy is in ATTACK and close enough, it chips the player's health on a cooldown (so contact isn't a per-frame machine-gun) and shoves the player along the contact normal — knockback that buys a moment of breathing room and makes a hit feel like a hit.

function contactDamage(e, player, dist) {
  if (e.state !== 'ATTACK' || dist > 26) return;
  if (e.hitCool > 0) return;                // per-enemy attack cooldown

  player.hp -= 6;
  e.hitCool = 0.7;                            // can't hit again for 0.7s

  const dx = player.x - e.x, dy = player.y - e.y;
  const d = Math.hypot(dx, dy) || 1;
  player.vx += (dx / d) * 5;                    // knockback along contact normal
  player.vy += (dy / d) * 5;
  player.flash = 0.25;                         // brief hit-flash for feedback
}

Decrement e.hitCool by STEP each update and you have a clean, readable damage rhythm — no spammy frame-rate-dependent chip damage, just a deliberate bite every fraction of a second.

Common pitfalls

  • Enemies clump into one blob. Pure seek sends everyone to the same point. Add separation — the sum of away-vectors from close neighbors — and the crowd self-spaces. Tune the separation radius to roughly the enemy's diameter.
  • State thrash at the aggro boundary. If enter and exit use the same range, an enemy on the edge flips CHASE / PATROL dozens of times a second. Use hysteresis: a tight enter threshold and a looser leave threshold, with a gap between them.
  • Spawn floods. An unbounded spawner will happily create thousands of enemies and bury the frame rate. Cap the active count (and ideally pool enemy objects so you're not allocating every spawn).
  • AI too perfect or too dumb. An enemy that tracks you with zero error feels robotic and unfair; one that wanders aimlessly feels broken. Add a touch of reaction delay or noise — the brief IDLE pause, a small jitter on the seek target — so it feels alive without being unbeatable.
  • Frame-rate-dependent behavior. If you scale enemy movement or cooldowns by a variable dt, the difficulty changes with the monitor. Do all AI movement inside the fixed step with constant per-step amounts.

Exercises

  1. A ranged enemy that shoots. Add a SHOOT state: instead of closing to melee, the enemy keeps its distance and fires a projectile at the player on a cooldown. You'll need a tiny bullet array (reuse the pooling idea from the spawner) and a "preferred range" it tries to hold via seek-toward / flee-from.
  2. Line-of-sight so walls block aggro. Right now enemies see through everything. Add a few wall rectangles and, before letting PATROL → CHASE fire, cast a ray from enemy to player and bail if it crosses a wall. Suddenly cover matters and the player can break pursuit by ducking behind something.
  3. A "flee when low health" state. Give enemies their own HP and a FLEE state entered when it drops below a threshold: invert seek (steer away from the player) until they've recovered or escaped. Watch how one extra state changes the whole feel of a fight.

What's next

Episode 07 — Scenes, score & UI. We've got a player, juice, and now an opponent — the raw mechanic is fun. Next we wrap it in an actual game: a title screen, a play scene, and a game-over screen wired together by a scene manager; a score that ticks up as you clear waves; lives and a HUD; and the loop that sends you back to the title to try again. Same fixed-step engine, finally dressed as something you'd ship.