Rebuilding Galaga in One File with Phaser 3: Formations, Dive-Bombs, and the Tractor Beam


Galaga is not Space Invaders with nicer sprites. Its aliens arrive along curved entry paths, hold a swaying formation, break ranks to dive at you, and one of them can drag your ship away with a tractor beam. This build log rebuilds those behaviours as small state machines inside a single Phaser 3 HTML file — no image files, no audio files, nothing but code you can read top to bottom.

Controls: Left/Right arrows (or A/D) move, Space fires, and on a phone you hold the left or right half of the screen to move and fire. Add ?mode=bot to the address to watch the autopilot play.

What We’re Building and Why

This is a Friday game build: a complete Galaga-style fixed shooter in one HTML file, running Phaser 3.80.1 from the jsDelivr CDN. Every sprite — player ship, aliens, bullets, stars, explosions — is drawn at runtime with Phaser’s Graphics API, so the file you copy is the whole game.

We already built Space Invaders and Pac-Man on this site. Galaga is the more interesting build because almost everything that makes it feel alive is a behaviour rather than a sprite: aliens enter on curves, the formation breathes, individual aliens leave and come back, and one specific alien can capture your ship and hand it back to you as a second gun.

The plan is deliberately not pixel-perfect. We are rebuilding the rules — entry paths, sway, dive-bombs, the tractor beam, the Challenging Stage — and letting the art be whatever a few fillTriangle calls produce. If you want the historical detail, the Galaga Wikipedia entry is the reference we used throughout, and the genre context lives under fixed shooter.

Honesty and Sources

This post is written from documentation, the Wikipedia record for Galaga, and the source code of the game below. No hands-on playtesting or benchmarking was done for this build, and no performance numbers are claimed. The only automated check was a 25-second headless-browser run of the built-in bot mode, which recorded no script errors. It says nothing about how the game feels.

The prose describes design decisions and Phaser APIs, checked against the Phaser download page and the concept docs linked in the walkthrough. If the code and the prose disagree, trust the code.

Galaga in 1981: A Two-Minute History

Galaga is a 1981 fixed shooter developed and published by Namco, with Midway handling North American distribution. It reached Japanese arcades in September 1981 and American ones that November, as the second entry in the Galaxian series after 1979’s Galaxian.

The team was small. Shigeru Yokoyama directed, Toru (Tetsu) Ogawa programmed, Hiroshi Ono designed many of the sprites, including the player ship and the Boss Galaga, and Nobuyuki Ohnogi wrote the music. Yokoyama made it after King & Balloon, the first of two games he was tasked with, and initial planning took about two months. The hardware moved from the older Namco Galaxian board to a new Namco Galaga board — the same board used by Bosconian (also 1981) and Dig Dug (1982).

Two design stories are worth keeping. The tractor beam came from a film in which a ship was captured by a circling laser; the original reward for rescuing your fighter was an extra life, and it was changed to a dual fighter instead. And the Challenging Stage started as a bug: Ogawa reported that enemies were flying off-screen instead of into formation, and the team kept the behaviour as a feature. The bonus-stage idea itself drew on Pac-Man intermissions and Rally-X bonus stages, and the bonus stage is the general name for that kind of break from normal play.

Early location tests underperformed because players could get far on a single coin, so Namco told the team to raise the difficulty. Separately, the operator manual notes that enemies grow more aggressive as the game progresses, and our build follows both ideas. It went on to become one of the most successful titles of the golden age of arcade video games, appearing on Japanese and American arcade charts through 1987.

Modelling the Formation

A formation is just an array of slot coordinates. Each alien owns a row and a column, and every frame the game writes its position from that slot plus a shared sway offset. Entry paths are separate: aliens spawn off-screen and follow a quadratic curve into their slot.

That separation is the single most useful idea in this build. The formation does not “move” — it is a lookup table that gets re-read every frame. Sway is one sine wave applied to every slot at once, so the whole grid breathes in sync without any alien knowing about any other alien.

var SLOT_X0 = 60, SLOT_DX = 52, ROW_Y = [120, 162, 204];
function slotX(col) { return SLOT_X0 + col * SLOT_DX; }

// every frame, for aliens in the 'formation' state:
e.sprite.x = slotX(e.col) + this.swayOffset;
e.sprite.y = e.slotY;

The layout is three rows: four Boss Galaga on top, then two rows of eight. Bosses take two hits, and in our build their texture swaps from boss to bossHit after the first one so you can see the damage. The two-hit rule is straight from the Galaga record — Galaxian’s flagships only took one.

Here is how the three games in this lineage differ, which is a decent map of what each one added:

Behaviour Space Invaders (1978) Galaxian (1979) Galaga (1981)
Formation Grid of aliens Formation; aliens dive-bomb toward the bottom Formation; aliens dive, and in our build they return to their slot
Entry Not covered here Aliens appear in formation toward the top of the screen Fly in from the top and sides into formation
Flagship None Galaxian Flagships, one hit each Four Boss Galaga, two hits each
Enemy fire Aliens shoot at the player Divers shoot as they attack Divers shoot; a Boss can also use a tractor beam
Bonus round None None Challenging Stage on stage 3, then every 4th

How Dive Paths Work

A dive is a second curve. When an alien leaves formation, the game records its current position as the start, picks a control point off to one side, and aims the end point below the screen. The alien travels that quadratic Bezier, fires, then wraps to the top and eases back into its slot.

Quadratic Bezier interpolation is three points and one parameter, which keeps the code short. A Bezier curve is normally described with a t from 0 to 1; we just advance t by speed * delta each frame instead of using a tween, so the alien can pause mid-path while it opens a tractor beam.

// quadratic bezier: p0 start, p1 control, p2 end
var mt = 1 - t;
e.sprite.x = mt*mt*p0.x + 2*mt*t*p1.x + t*t*p2.x;
e.sprite.y = mt*mt*p0.y + 2*mt*t*p1.y + t*t*p2.y;

When t reaches 1 the alien is off the bottom of the screen. It teleports to just above the top, switches to a returning state, and eases toward its slot with a simple normalised step. That wrap is what keeps the pressure on without ever letting the alien count drop.

Aggression scales per stage, matching the record’s note that enemies grow more aggressive with more projectiles and faster dives. In our version the dive interval shrinks, the number of simultaneous divers rises, and enemy bullet speed increases with the stage number.

Capture and Rescue as a State Machine

The tractor beam is a state machine with three owners: the boss, the player, and the captured ship. A diving Boss can open a beam; if the player is inside it, the ship is captured and a life is lost. Shooting that boss mid-dive rescues the ship as a dual fighter.

The three branches are the whole feature:

  1. Boss dives, opens beam, player is inside it → the player loses a life, and a small orange fighter appears attached to the boss. The boss finishes its dive and returns to formation with your ship riding underneath it.
  2. You destroy that boss while it is diving → rescue. The captured fighter merges with yours as a dual fighter: two guns firing at once, and a wider collision box.
  3. You destroy that boss while it is sitting in formation → the captured fighter turns against you and joins the formation as an enemy.

Branch 3 is the cruel one and it is the reason the original is memorable. The dual fighter’s larger hitbox is a real trade-off, not a free upgrade — you are easier to hit while you are stronger.

if (e.holdsShip && this.capturedShip && this.capturedShip.boss === e) {
  if (e.state === 'dive') { this.dual = true; }        // rescue
  else { this.spawnTurncoat(e.row, e.col); }           // turns on you
  this.capturedShip.sprite.destroy();
  this.capturedShip = null;
}

Code Walkthrough

The whole game is one scene class. Textures are generated once with Phaser Graphics, the scale manager fits a 480x640 canvas to any screen, and each behaviour — entry, sway, dive, beam, capture — is a small branch inside the update loop.

The scale config. The Scale Manager handles fitting and centring, which matters because the game is embedded in an iframe on the site.

var config = {
  type: Phaser.AUTO,
  parent: 'game',
  width: 480, height: 640,
  backgroundColor: '#0b0620',
  scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH },
  scene: [GalagaScene]
};
new Phaser.Game(config);

Generated textures. Every sprite is drawn once into a canvas texture and then reused. This is what keeps the build to a single file with no external assets. Phaser 3.80.1 comes from the jsDelivr package page; the site standard is Phaser 3 even though v4 is the current stable release.

var g = this.add.graphics();
g.fillStyle(0x9dff6b, 1);
g.fillTriangle(14, 0, 0, 24, 28, 24);
g.fillStyle(0xff4d6d, 1);
g.fillRect(4, 16, 20, 5);
g.fillStyle(0xffffff, 1);
g.fillRect(12, 4, 4, 8);
g.generateTexture('boss', 28, 26);
// ...other textures follow, then g.destroy()

The capture state machine is the snippet in the previous section — three branches, one flag on the boss (holdsShip), one on the scene (capturedShip), and one on the player (dual).

Bot mode. Append ?mode=bot to the URL and an autopilot takes over. It dodges incoming bullets, slides under the lowest diving alien, fires constantly, and starts or restarts the game by itself. It exists as a test hook, and it is also a decent way to watch the formation logic run without touching the keyboard.

if (this.botMode) {
  dir = this.botDir();          // dodge, then chase the lowest diver
  // firing is decided elsewhere: var firing = this.botMode || this.cursors.space.isDown || ...
}

Input comes through the Input plugin: arrow keys or A/D to move, Space to fire, and a touch fallback where holding the left or right half of the screen moves and fires. Movement is scaled by the delta the game loop hands to update, so speed does not depend on the frame rate. Short animations — explosions, the pulsing title, floating score messages — use tweens.

One deliberate omission: this build does not use Arcade Physics. Aliens in a formation need to be placed, not simulated, and bullet-versus-alien checks are simple axis-aligned box tests. If you are building something with bouncing or gravity, the physics docs are where to start.

What I Learned

Three things stuck. State machines beat nested conditionals every time — the tractor beam looks complicated until you write down the three states. Generating textures in code keeps a build to one file, which makes it trivial to embed and share. And curves are cheap: a quadratic Bezier is three points and one number, and it is the difference between aliens that slide and aliens that fly.

The other lesson is about scope. The original Galaga has enemies that morph into other types (the Galaxian Flagship and the Midori) and a stage counter that reportedly rolls over after 255, a kill screen claim that the Galaga article itself marks as coming from an unreliable source, so treat it as folklore rather than fact. None of that is required for the game to feel like Galaga. Formation, dive, capture, rescue — four behaviours, and the rest is decoration.

FAQ

Why does the Boss Galaga take two hits?

Because the original made its leaders tougher than the rest. In the 1981 original the four large Boss Galaga aliens sit atop the formation and take two hits, where Galaxian’s flagships took only one. In our build the boss carries hp: 2, swaps to a pink texture on the first hit, and only dies on the second.

What happens if you shoot the boss while it’s still in formation?

Your captured fighter turns against you. The record is explicit: destroying the boss while it is still in formation makes the captured fighter turn against the player, and it returns in a later level as part of the formation. In our build it spawns immediately as a new formation enemy in the boss’s old slot, wearing the orange player-ship texture so you can see what you did.

Why does Galaga get harder as it goes on?

Because Namco asked for a harder game. Early location tests underperformed because players could get far on one coin, so the team was instructed to raise the difficulty, and enemies grew more aggressive with more projectiles and faster dives. Our version does the same thing numerically: the dive timer shortens, more aliens dive at once, and enemy bullets speed up with each stage.