# 3. Space Invaders Invader Formation
Part of [[Space Invaders]]. Previous: [[2. Space Invaders Player Cannon and Bullets]]. Next: [[4. Space Invaders Invader Fire Bunkers and UFO]].
## 3.1 The rules
1. The rack is 5 rows × 11 columns. Row 0 (top) is the squid, rows 1–2 the crab, rows 3–4 the octopus.
2. It moves in **steps** of a fixed size, not smoothly.
3. Before a step, check the **living** columns at the edges. If the next step would push one past the bound, the rack **drops one row and reverses** instead of stepping sideways.
4. The time between steps shrinks as invaders die. In the arcade this happened because the hardware drew fewer sprites per frame. Here it's deliberate: a linear map from 0.8 s (55 alive) to 0.05 s (1 alive).
Rule 3 is why shooting out a whole edge column is a strategy: the rack then travels further before turning.
## 3.2 FormationModel (pure C#)
All the rules live here, with no `UnityEngine`. Positions are computed from the origin (the top-left cell) and spacing, so nothing per invader needs updating except when the rack steps.
```csharp
using System;
/// <summary>
/// The invader rack as pure data: which invaders are alive, where the rack is, and how it marches.
/// Classic rules: the rack steps sideways on a timer; when any living invader would cross an edge,
/// the whole rack drops one row and reverses. Fewer invaders = shorter step interval (it speeds up).
/// No UnityEngine types, so it is unit-testable.
/// </summary>
public sealed class FormationModel
{
readonly bool[,] _alive;
float _timer;
public FormationModel(int rows, int columns, float spacingX, float spacingY, float leftBound, float rightBound,
float stepX = 0.125f, float dropY = 0.25f, float slowInterval = 0.8f, float fastInterval = 0.05f)
{
if (rows <= 0 || columns <= 0)
throw new ArgumentException("Formation needs at least one row and column.");
Rows = rows;
Columns = columns;
SpacingX = spacingX;
SpacingY = spacingY;
LeftBound = leftBound;
RightBound = rightBound;
StepX = stepX;
DropY = dropY;
SlowInterval = slowInterval;
FastInterval = fastInterval;
_alive = new bool[rows, columns];
Reset(0f, 0f);
}
public int Rows { get; }
public int Columns { get; }
public float SpacingX { get; }
public float SpacingY { get; }
public float LeftBound { get; }
public float RightBound { get; }
public float StepX { get; }
public float DropY { get; }
public float SlowInterval { get; }
public float FastInterval { get; }
/// <summary>Top-left invader position (row 0 = top row).</summary>
public float OriginX { get; private set; }
public float OriginY { get; private set; }
public int Direction { get; private set; } = 1;
public int AliveCount { get; private set; }
public int StepCount { get; private set; }
public event Action<int> Stepped; // arg: step index, for the four-note march sound
public event Action Dropped;
public void Reset(float originX, float originY)
{
OriginX = originX;
OriginY = originY;
Direction = 1;
StepCount = 0;
_timer = 0f;
for (var r = 0; r < Rows; r++)
for (var c = 0; c < Columns; c++)
_alive[r, c] = true;
AliveCount = Rows * Columns;
}
public bool IsAlive(int row, int column) => _alive[row, column];
public float X(int column) => OriginX + column * SpacingX;
public float Y(int row) => OriginY - row * SpacingY;
public bool Kill(int row, int column)
{
if (!_alive[row, column])
return false;
_alive[row, column] = false;
AliveCount--;
return true;
}
/// <summary>Interval between steps: linear from slow (full rack) to fast (one left).</summary>
public float StepInterval
{
get
{
var total = Rows * Columns;
if (total <= 1 || AliveCount <= 1)
return FastInterval;
var t = (AliveCount - 1f) / (total - 1f); // 1 = full, 0 = last one
return FastInterval + (SlowInterval - FastInterval) * t;
}
}
/// <summary>Advance time; returns the number of steps taken this call.</summary>
public int Tick(float dt)
{
if (AliveCount == 0)
return 0;
_timer += dt;
var steps = 0;
while (_timer >= StepInterval && steps < 4) // cap catch-up after a hitch
{
_timer -= StepInterval;
Step();
steps++;
}
return steps;
}
public void Step()
{
if (AliveCount == 0)
return;
FindLiveColumns(out var minCol, out var maxCol);
var nextLeft = X(minCol) + StepX * Direction;
var nextRight = X(maxCol) + StepX * Direction;
if (nextRight > RightBound || nextLeft < LeftBound)
{
OriginY -= DropY;
Direction = -Direction;
Dropped?.Invoke();
}
else
{
OriginX += StepX * Direction;
}
Stepped?.Invoke(StepCount++);
}
/// <summary>Lowest living row's world Y (for "invaders reached the ground").</summary>
public float LowestY()
{
for (var r = Rows - 1; r >= 0; r--)
for (var c = 0; c < Columns; c++)
if (_alive[r, c])
return Y(r);
return float.PositiveInfinity;
}
/// <summary>The bottom-most living invader in a column, or -1. Only it may shoot.</summary>
public int BottomRow(int column)
{
for (var r = Rows - 1; r >= 0; r--)
if (_alive[r, column])
return r;
return -1;
}
/// <summary>
/// Picks a shooting column. With probability `aimChance`, the living column nearest the player's X;
/// otherwise a random living column. Returns -1 if none.
/// </summary>
public int PickShooterColumn(Random rng, float playerX, float aimChance)
{
var best = -1;
var bestDist = float.MaxValue;
var liveColumns = 0;
for (var c = 0; c < Columns; c++)
{
if (BottomRow(c) < 0)
continue;
liveColumns++;
var d = Math.Abs(X(c) - playerX);
if (d < bestDist)
{
bestDist = d;
best = c;
}
}
if (liveColumns == 0)
return -1;
if (rng.NextDouble() < aimChance)
return best;
var pick = rng.Next(liveColumns);
for (var c = 0; c < Columns; c++)
{
if (BottomRow(c) < 0)
continue;
if (pick-- == 0)
return c;
}
return best;
}
void FindLiveColumns(out int min, out int max)
{
min = Columns;
max = -1;
for (var c = 0; c < Columns; c++)
{
if (BottomRow(c) < 0)
continue;
if (c < min) min = c;
if (c > max) max = c;
}
}
}
```
Details that matter:
- **`Tick` caps catch-up at 4 steps.** After a hitch (a GC spike, or alt-tabbing), the rack would otherwise teleport.
- **`Stepped` carries a step index**, so the march sound and the two-frame animation stay in sync.
- **`PickShooterColumn`** is here, not in the shooter, because "which columns are alive" is model knowledge (part 4).
## 3.3 Invader
The invader is just a view and a hit target. Its row and column come from the grid, and `Snap` moves it and flips its frame on odd and even steps.
```csharp
using UnityEngine;
/// <summary>One invader. Position and life live in the FormationModel; this is the view and hit target.</summary>
[RequireComponent(typeof(SpriteRenderer))]
public sealed class Invader : MonoBehaviour, IShootable
{
[SerializeField] Sprite frameA;
[SerializeField] Sprite frameB;
InvaderGrid _grid;
SpriteRenderer _renderer;
public int Row { get; private set; }
public int Column { get; private set; }
void Awake() => _renderer = GetComponent<SpriteRenderer>();
public void Bind(InvaderGrid grid, int row, int column)
{
_grid = grid;
Row = row;
Column = column;
name =
quot;Invader r{row} c{column}";
}
public void Snap(Vector2 position, int step)
{
transform.position = position;
if (frameA != null && frameB != null)
_renderer.sprite = (step & 1) == 0 ? frameA : frameB;
}
public bool TakeHit(Bullet bullet)
{
if (!bullet.FromPlayer)
return false; // invader shots pass through other invaders
_grid.Kill(this);
return true;
}
}
```
Make three prefabs: squid, crab and octopus. Each has a `SpriteRenderer`, a trigger `BoxCollider2D` slightly smaller than the sprite, layer `Invader`, and an `Invader` component with two frames.
## 3.4 InvaderGrid
The grid spawns the 55 invaders **once**, in `Awake`, and reuses them every wave (`BeginWave` re-activates them). It ticks the model when the director tells it to (part 5), and after each step it snaps every living invader to its cell and plays the next of four march notes.
```csharp
using System;
using UnityEngine;
/// <summary>
/// Spawns one Invader per FormationModel cell, ticks the model, and snaps every invader to its
/// cell after each step (the arcade moves the rack in discrete steps, not smoothly).
/// Two-frame animation: each step flips the sprite, which is most of the classic look.
/// </summary>
public sealed class InvaderGrid : MonoBehaviour
{
[SerializeField] Invader[] rowPrefabs = new Invader[5]; // row 0 (top) .. row 4
[SerializeField] int columns = 11;
[SerializeField] Vector2 spacing = new Vector2(0.5f, 0.45f);
[SerializeField] Vector2 startTopLeft = new Vector2(-2.5f, 3.2f);
[SerializeField] float leftBound = -3.4f;
[SerializeField] float rightBound = 3.4f;
[SerializeField] AudioSource marchSource;
[SerializeField] AudioClip[] marchNotes = new AudioClip[4];
Invader[,] _invaders;
public FormationModel Model { get; private set; }
public event Action<Invader> InvaderKilled;
public event Action Cleared;
void Awake()
{
Model = new FormationModel(rowPrefabs.Length, columns, spacing.x, spacing.y, leftBound, rightBound);
Model.Stepped += OnStepped;
_invaders = new Invader[Model.Rows, Model.Columns];
for (var r = 0; r < Model.Rows; r++)
{
for (var c = 0; c < Model.Columns; c++)
{
var inv = Instantiate(rowPrefabs[r], transform);
inv.Bind(this, r, c);
_invaders[r, c] = inv;
}
}
}
/// <summary>Start a wave: everyone alive, rack at the start position minus the wave drop.</summary>
public void BeginWave(float extraDrop)
{
Model.Reset(startTopLeft.x, startTopLeft.y - extraDrop);
foreach (var inv in _invaders)
inv.gameObject.SetActive(true);
SnapAll();
}
public void Tick(float dt) => Model.Tick(dt);
public Vector2 CellPosition(int row, int column) => new Vector2(Model.X(column), Model.Y(row));
public Invader BottomInvader(int column)
{
var r = Model.BottomRow(column);
return r < 0 ? null : _invaders[r, column];
}
internal void Kill(Invader invader)
{
if (!Model.Kill(invader.Row, invader.Column))
return;
invader.gameObject.SetActive(false);
InvaderKilled?.Invoke(invader);
if (Model.AliveCount == 0)
Cleared?.Invoke();
}
void OnStepped(int step)
{
SnapAll();
if (marchSource != null && marchNotes.Length > 0 && marchNotes[step % marchNotes.Length] != null)
marchSource.PlayOneShot(marchNotes[step % marchNotes.Length]);
}
void SnapAll()
{
for (var r = 0; r < Model.Rows; r++)
for (var c = 0; c < Model.Columns; c++)
if (Model.IsAlive(r, c))
_invaders[r, c].Snap(CellPosition(r, c), Model.StepCount);
}
}
```
Setup: an empty `InvaderGrid` object with the five row prefabs in this order: squid, crab, crab, octopus, octopus. Add an `AudioSource` with four short low notes for the march.
> [!note] Give invaders a Kinematic Rigidbody2D
> Add a **Rigidbody2D** to each invader prefab: Body Type **Kinematic**, **Use Full Kinematic Contacts** on. There are two reasons:
> 1. Two colliders with no Rigidbody2D (an invader and a bunker cell) never produce trigger callbacks. Part 4's "the rack erases the bunkers it marches through" needs one of them to have a body.
> 2. Moving colliders that have no body is supported, but it's the slow path in Physics 2D.
>
> `Snap` sets `transform.position`, which teleports a kinematic body. That's correct for a stepping rack, because we *want* a teleport rather than a swept move. Not profiled here.
## 3.5 Design lens: an accidental difficulty curve
The speed-up is the best-known difficulty curve in games: the better you play, the harder it gets, and the last invader is frantic. [[Level Up! (Review)]] talks about pacing as tension and release. Here, a cleared wave is the release, and the next wave starting lower (part 5) raises the baseline tension. Try a non-linear curve in [[Game Balance and Dynamic Difficulty]] terms: an ease-in curve keeps the first half calm and makes the end brutal.
## Exercises
1. Replace the linear interval with an `AnimationCurve` evaluated on `AliveCount / total`. Write a test for its endpoints.
2. Move only *one row per frame*, as the arcade effectively did: the rack ripples instead of jumping as a block. (Hint: snap row `StepCount % Rows` each frame.)