Build a Galaga-Style Shooter in Phaser 3: Formations, Dives, and the Dual Fighter


You build a Galaga-style shooter in Phaser 3 with a single Scene, a 960×540 canvas, and no physics engine: enemies are plain objects that follow quadratic Bézier paths into a swaying formation, a dive timer sends one formation member down its own curved path while it fires, and about forty lines of rectangle tests resolve every collision.

This guide is based on Phaser’s official documentation, the Galaga, Galaxian and Space Invaders entries on Wikipedia, and the source of the build embedded on this page; we did not run the arcade hardware.

The game below was written for this site and committed at /games/galaga-phaser.html; every behavioural claim here was checked against that file. Play it first — the rest of the article explains how each piece works.

Why Galaga is a good beginner shooter

Galaga is a good first shooter because the whole game fits on one screen and breaks into five small systems — a formation, a dive scheduler, two bullet lists, a collision pass, and the capture state machine — with no scrolling camera, no tilemap, and no level editor to learn before anything moves.

The build on this page is 960×540 and never leaves that box. It also never configures a physics engine, which is worth dwelling on because “you need Arcade Physics for collisions” is the assumption most beginners start from. Phaser treats physics as an optional Scene plugin: it is installed only when the game config’s physics.default is set to arcade or matter, or when a Scene asks for it explicitly, as the Phaser Scene documentation describes. This build asks for neither. Bullets and aliens are moved by hand and compared with Math.abs differences, which for a game with two dozen sprites is less code than wiring a physics world and tuning body sizes.

The trade is real: you give up velocity, drag, bounce and the collider system, so every movement rule is yours to write. For a fixed shooter where nothing bounces, that is an easy win.

How Galaga compares to Galaxian and Space Invaders

Galaga keeps Space Invaders’ fixed single-screen format, borrows Galaxian’s diving attackers, and adds two things neither had: a boss enemy that survives one hit, and a tractor beam that steals your ship and can be reversed into a second cannon.

Feature Space Invaders (1978) Galaxian (1979) Galaga (1981)
Formation movement Five rows of eleven move left and right as a group, stepping down each time they reach a screen edge Aliens dive toward the bottom of the screen while shooting projectiles Aliens fly into formation from the top and sides of the screen, then dive while shooting
Enemy fire Aliens fire projectiles at the cannon, costing a life on contact Divers shoot projectiles on the way down Divers shoot projectiles on the way down
Special enemies A mystery ship crosses the top of the screen for bonus points Galaxian Flagships fly with two escorts and take a single shot to destroy Four Boss Galaga sit atop the formation and take two shots each
Signature mechanic Stationary bunkers that are worn down by enemy fire from above and by your own shots from below Shooting a flagship together with both escorts awards bonus points Tractor-beam capture; rescuing the captured fighter yields a dual fighter with more firepower and a larger hitbox

Each row above is drawn from the corresponding Wikipedia entry: the Space Invaders, Galaxian and Galaga articles. One thing the table deliberately does not contain is a “build effort” row. How long each of these takes to write is our judgement, not a documented fact: the Galaga build here is the largest of the three, because the capture system and the per-type dive paths add state that Space Invaders never needs. Treat that sentence as an opinion and the table as sourced.

What you’re building

Five systems, each finishable in one sitting:

  • Player — moves along the bottom at a fixed speed, fires upward on a cooldown, and keeps a bullet count rather than a bullet pool class.
  • Formation — a table of rows and columns, where each alien owns a path into its slot and a sway function that keeps the whole grid breathing.
  • Dives — a timer that picks one alien in formation and gives it a new path toward your current position, with a shot budget attached.
  • Capture and rescue — a boss that diverts into a tractor-beam dive, a captured ship that rides above it, and a freed ship you have to catch.
  • Flow — stage clear, a harder next stage, challenge stages, and a final stage that ends the game.

Phaser scene setup

One Scene carries the whole game: create() builds textures, the player, the starfield and the three arrays, while update() delegates to a tick() that moves the player, the aliens, the bullets, the capture animation and the collision pass in a fixed order.

var W = 960, H = 540;

new Phaser.Game({
  type: Phaser.AUTO,
  width: W,
  height: H,
  parent: 'game',
  backgroundColor: '#05010f',
  scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.NO_CENTER },
  scene: [GalagaScene]
});

There is no physics key in that config, and nothing in the file calls this.physics. The containers are three ordinary arrays declared in create():

this.enemies = []; this.pBullets = []; this.eBullets = [];

Sprites are drawn from pixel maps rather than image files: pixTex() walks an array of strings, fills one rectangle per palette character, and calls generateTexture(). No asset pipeline, one HTML file — the right trade for a tutorial build, the wrong one for a game with an artist.

How the formation works

The formation is a table of rows with explicit column lists, not a rectangle: four Boss Galaga in row 0 at columns 3 to 6, eight flyers in row 1 at columns 1 to 8, ten drones in row 2 at columns 0 to 9, and a second drone row at stage 2 and later. Each alien then converts its column into an x position through formPos(), which is also where the sway lives.

spawnFormation() {
  var layout = [{ type: 'boss', row: 0, cols: [3, 4, 5, 6] }, { type: 'fly', row: 1, cols: [1, 2, 3, 4, 5, 6, 7, 8] },
    { type: 'bee', row: 2, cols: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] }];
  if (this.stage >= 2) { layout.push({ type: 'bee', row: 3, cols: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] }); }
  var idx = 0;
  for (var r = 0; r < layout.length; r++) {
    for (var c = 0; c < layout[r].cols.length; c++) {
      var e = this.makeEnemy(layout[r].type, layout[r].row, layout[r].cols[c]);
      var g = Math.floor(idx / 8), k = idx % 8, side = g % 2;
      e.delay = 0.5 + g * 1.5 + k * 0.13;
      var fp = this.formPos(e);
      var sx = side ? W * 0.72 : W * 0.28;
      var d = side ? 1 : -1;
      e.segs = this.buildPath({ x: sx, y: -40 }, { x: sx + d * 140, y: 230 }, [{ x: W / 2 - d * 160, y: 350 }, { x: fp.x, y: fp.y, dyn: true }]);
      e.speed = 430;
      this.enemies.push(e);
      idx++;
    }
  }
}

Read the sx line closely: it is where this build departs from the arcade original. Every alien starts at y: -40 — above the top edge — in one of two lanes at 28% or 72% of the width, alternating every eight aliens. Wikipedia says the original aliens “fly into formation from the top and sides of the screen”; this build enters from the top only, then swings out toward its side on the way in. Each path is a chain of quadratic Bézier segments from buildPath(): launch, a swing out to W/2 ± 160 at y 350, and a final segment marked dyn: true that retargets to the live formation slot every frame, so a moving slot stays a valid destination.

followPath() walks that chain by advancing a normalised parameter rather than a tween:

e.t += (e.speed * dt) / len;
var t = Math.min(1, e.t), u = 1 - t;
e.spr.x = u * u * seg.p0.x + 2 * u * t * seg.p1.x + t * t * seg.p2.x;
e.spr.y = u * u * seg.p0.y + 2 * u * t * seg.p1.y + t * t * seg.p2.y;

Two consequences follow. First, no tween objects exist for aliens at all — tweens in this file are reserved for text fades and explosion particles. Second, because the speed is normalised by segment length, a short segment and a long segment take different times but the same pixels-per-second, which is what keeps the entry looking uniform.

The formation itself never stops moving:

formPos(e) {
  var spread = 1 + 0.06 * Math.sin(this.swayT * 1.7);
  return { x: W / 2 + (e.col - 4.5) * DX * spread + Math.sin(this.swayT * 0.9) * 55, y: ROW_Y[e.row] || 100 };
}

DX is 58 pixels of slot spacing and ROW_Y is [84, 124, 164, 204]. The spread term breathes the grid wider and narrower, and the trailing sine slides the whole block sideways. Any alien in the form state is simply set to formPos() every frame, so the sway costs nothing per alien — no per-sprite tween, no per-sprite state.

Dive attacks and enemy bullets

A dive is what turns a static grid into Galaga: once no alien is still entering, a timer calls launchDive(), which counts the aliens already committed to an attack, caps that count at 2 + stage (maximum eight), picks one alien whose state is exactly form, and hands it a fresh multi-segment path aimed at your current x position.

launchDive() {
  var divers = 0, forms = [], i, e;
  for (i = 0; i < this.enemies.length; i++) {
    e = this.enemies[i];
    if (!e.alive) { continue; }
    if (e.state === 'dive' || e.state === 'beamdive' || e.state === 'beaming' || e.state === 'leave' || e.state === 'holding') { divers++; }
    else if (e.state === 'form') { forms.push(e); }
  }
  var maxDivers = Math.min(2 + this.stage, 8);
  if (divers >= maxDivers || forms.length === 0) { return; }
  var pick = Phaser.Utils.Array.GetRandom(forms);

The forms filter is the important line. A dive can only start from an alien that has finished entering and is not already diving, so two paths never fight over one sprite, and the concurrent-diver cap means the screen cannot empty itself in a single frame. The scheduler that calls it lives in updateFlow() and speeds up with every stage:

this.diveT -= dt;
if (this.diveT <= 0) {
  this.launchDive();
  this.diveT = Math.max(0.45, 2.0 - this.stage * 0.17) * rand(0.7, 1.3);
}

Each enemy type gets a different curve in startDive(): drones cut sideways, drop to 82% of the screen height and exit; flyers swing out to one side, cross to the other, then leave; bosses take a tighter, slower descent. All three are single quadratic chains — no easing functions, no tween. The Sine.easeIn shape you would reach for in a tween is not here; the curve is in the control points.

Firing is attached to the dive rather than to the formation. fireEnemy() gives each diver a shot budget (1 before stage 2, 2 from stage 2, 3 from stage 5), and from stage 2 the shot is aimed:

ang = Math.atan2(PY - e.spr.y, this.px - e.spr.x) + rand(-0.08, 0.08);
ang = clamp(ang, Math.PI / 2 - 0.65, Math.PI / 2 + 0.65);

The clamp is the detail that makes aimed fire fair: shots can lean up to about 37° off vertical but never sideways, so a diver cannot shoot horizontally across the screen. Enemy bullets live in this.eBullets and are capped at twelve in flight, which is a cheap way to keep a late stage from becoming unreadable.

The dual fighter mechanic

The dual fighter comes down to three moments: a boss diverts into a beam dive, the beam captures your ship and costs you a life, and the captured ship rides above that boss until you destroy it — at which point the freed fighter spins down toward your x position and docks if you are under it.

The capture starts when a boss is chosen for a dive and the conditions allow it: no ship already captured, no beam already active, not already dual, and a coin flip. The boss flies to a point above you and opens a cone for 3.2 seconds. If your ship is inside that cone when it has grown to 60% of its length, startCapture() runs a 1.4-second animation that drags the ship up, spins it and shrinks it — and when the animation ends, this.lives-- runs before the captured ship is attached. Capture costs a life; that is not cosmetic.

if (f >= 1) {
  this.capAnim = null;
  this.player.setVisible(false).setRotation(0).setScale(1);
  this.lives--;
  if (this.lives <= 0) {
    this.overPending = true; this.overT = 1.4;
    Sfx.play('lose');
  } else {
    var spr = this.add.image(b.spr.x, b.spr.y - 24, 'captured').setDepth(4);
    this.capShip = { spr: spr, boss: b, state: 'held', life: 0 };
    b.holdsShip = true;
    this.respawnT = 1.5;
  }
  this.startLeave(b);
}

From then on the captor carries a flag, holdsShip, and killing any boss with that flag calls releaseShip(), which flips the captured ship into the rescue state. The rescue is a catch, not a gift: the freed fighter spins, drifts toward your current x at up to 230 pixels per second, descends at 200 pixels per second, and only docks when it reaches your row within 34 pixels horizontally. Miss it and it is gone after seven seconds. Docking sets dual, adds 1000 points, and from then on firePlayer() emits two bullets instead of one.

Here the build deliberately diverges from the arcade rule, and the difference is worth stating plainly because the original is stricter. In Galaga, according to the Wikipedia gameplay section, shooting the Boss Galaga “as they dive towards the player” rescues the fighter, while “destroying the Boss Galaga with the captured Fighter while it is in formation will instead cause it to turn against the player”. This build does not implement that penalty: the rescue triggers whenever the holding boss dies, in formation or mid-dive, and there is no turncoat ship. If you want the arcade behaviour, gate releaseShip() on the boss’s state — e.state === 'dive' || e.state === 'beamdive' — and spawn an enemy fighter on the other branch. That is a two-line change, and it is the first thing worth adding after the base game works.

Making each stage harder

Difficulty comes from four dials and no new code paths: the dive interval shrinks from 2.0 seconds toward a 0.45-second floor, the concurrent-diver cap rises by one per stage up to eight, every dive speed is multiplied by 1 + 0.07 * stage, and the shot budget per dive steps up twice. Stage 2 also adds the fourth drone row, which is the single biggest jump in the game because the formation takes noticeably longer to clear.

Two special stages break the rhythm: stages 3 and 7 spawn no formation at all. Thirty-two aliens cross the screen in scripted arcs, worth 100 points each, and clearing all of them awards 10,000. Clearing stage 8 ends the run with a victory screen. Extra ships arrive at 20,000, 60,000 and 120,000 points, capped at seven lives — a deliberate choice so a first playthrough can realistically reach stage 8.

Handling collisions, lives, and respawns

Every collision in the game is one of three rectangle comparisons inside checkCollisions(): your bullets against aliens, enemy bullets against you, and alien bodies against you. No collider objects, no overlap callbacks, no groups — just a nested loop over two arrays with a half-width and half-height test.

if (Math.abs(b.spr.x - e.spr.x) < e.w / 2 + 3 && Math.abs(b.spr.y - e.spr.y) < e.h / 2 + 7) {
  this.killBullet(b);
  this.hitEnemy(e);
  break;
}

The per-type w and h values are stored on each alien when it is created (bee 33×24, fly 33×21, boss 39×27), so a boss is genuinely a bigger target rather than a visually larger sprite with a drone’s hitbox. Bullets are marked alive = false and their sprites destroyed, then both arrays are filtered once per frame:

this.pBullets = this.pBullets.filter(function (q) { return q && q.alive; });
this.eBullets = this.eBullets.filter(function (q) { return q && q.alive; });

That filter is the entire object pool. There is no free list and no pre-allocation, which is fine at this scale: a dozen bullets per frame is nothing, and the code stays readable. Your own fire is rate-limited by a 0.16-second cooldown and a count check that allows a shot while two or fewer of your bullets exist — up to three in flight, and up to five once you are dual.

Losing a life is not a reset. If you are dual, the hit costs you the second cannon and 1.6 seconds of invulnerability instead of a life. Otherwise the ship explodes, lives drops, and after 1.4 seconds spawnPlayer() returns it to the centre with two seconds of blinking invulnerability. At zero lives the game-over screen takes over and R restarts.

Building with AI assistance

This game was written by an AI model from a brief and then audited against its own source. That audit is the useful part of the story: the prose an AI produces about code is often about the code it would have written, and the only reliable check is to open the file and compare. Four claims in the first draft of this article failed that check and were rewritten from the source.

That is the workflow worth copying. Give the model one system per prompt and name the primitives: “a quadratic Bézier chain walked by a normalised parameter” gets a usable answer where “make enemies attack” does not. Ask for the rule rather than the effect — “cap concurrent divers at 2 + stage” is testable; “make it feel like Galaga” is not. Keep the file short enough to read end to end, and when a model’s explanation and the committed code disagree, the code wins.

If you want a gentler starting point, our Space Invaders build guide has no diving and no capture system, and our Phaser space shooter tutorial covers the groups-and-bullets pattern this build replaces with arrays.

FAQ

Do I need Arcade Physics to build this?

No. Phaser installs physics as an optional Scene plugin, and this build never enables it: movement is per-frame position updates and collisions are Math.abs comparisons. Arcade Physics earns its place when you want gravity, bounce, drag or many overlapping bodies. For a fixed shooter with two dozen sprites, hand-written tests are shorter and easier to debug.

How faithful should a clone be to the original?

Faithful enough that the loop feels right, and honest about the rest. The sourced essentials are a starship at the bottom, aliens that fly into formation and dive while shooting, two-shot bosses, and a capture that costs a life and can be reversed into a dual fighter. Formation sizes, point values and dive timings in this build are our own choices; the arcade numbers are not in the sources used here, so we did not invent them.

Can an AI assistant build the whole game?

It can produce a working first version, and it will also produce confident sentences about code it did not write. Treat the model as a fast typist with good API recall and no memory of your file: give it one system at a time, run what it returns, and diff its explanation against the source. The gap between those two is where every real bug in this build was found.

What you learned

You now have four patterns you will reuse in every arcade remake: paths walked by arc length instead of tweens, a formation that is a table plus a sway function, a scheduler gated on state and a concurrent cap, and a collision pass you can read in one screen. Each is now a deliberate decision rather than an inherited framework default.

The Bottom Line

A Galaga-style shooter is a good second or third Phaser project: the rules fit on an index card, the code fits in one file, and the hard parts — path following, dive scheduling, capture state — are problems of state, not rendering. Build the formation first, get one alien diving, and add the beam last. The game is playable here; read its source alongside this article.

How This Guide Was Built

This article describes a game built for this site and committed at public/games/galaga-phaser.html. That file, not recollection, is the reference for every statement about behaviour, and every number quoted here (speeds, caps, intervals, point values) is read from it. Historical claims about Galaga, Galaxian and Space Invaders come from their Wikipedia entries, linked inline where they are used; the Phaser claims come from Phaser’s own documentation. The build’s file is public, so you can check any sentence in this article against the code that implements it.