Make a tower defense
Invaders come in waves along a road, and the player builds towers to stop them before they get through. You build it from data for towers and invaders, timers for the waves, a listener on what gets through, and objectives that say what winning is.
Quick start
npm create @v12-engine my-game -- --starter campaign
cd my-game && npm run devThe campaign's second mission, the Siege, is a tower defense: waves out of a war camp at night, a gate that shuts as each comes, towers and walls to hold them. The tutorial's chapter builds it. Its files: src/campaign/waves.ts (waves), missions/siege.ts (mission and gate), kills.ts and view/labels.ts (kills over each tower), src/waves-panel.ts (an editor panel for the waves).
Build it yourself
1. Waves on timers
const waveComes = defineTimer({ id: 'td.waveComes', run: (world) => startWave(world) })
const invaderComes = defineTimer<{ type: string }>({ id: 'td.invaderComes', run: (world, { type }) => world.spawn(type, ENEMY, world.map.point('camp')) })
world.timers.after(30, waveComes)
world.timers.every(1.2, invaderComes, { times: 20, first: 0, data: { type: 'skeleton' } })Keep the wave's state in a component (world.state(waves)) so it saves. See Timers.
2. A road
An order of your own walks each invader to the next point of world.map.path('road'), keeping its place in order.state so a save has it. See Write an order.
3. Lives
Make the road's end a region the world watches as an area. A listener of enteredArea takes a life and removes the invader. Run it through a hook type of your own (defineHookType) so a mod can change what one costs. See Watch an area.
4. Rules for building and targeting
- Nothing built on the road: a
canPlacehook that says no, with a reason. - Towers shoot the first in line: a
targetScorehook that scores by how far along the road a target is. - No builders: a command of your own (
defineCommand) that spawns the tower where the player clicks and takes its cost (spend).
5. Winning
const hold = defineObjective({ id: 'td.hold', text: 'objectiveHold' })
world.objectives.add(DEFENDER, hold, { progress: { value: 0, max: 10 } })
export const rules: Rules = { ...game, victory: objectiveVictory }Invaders that choose targets
Seat a mission brain with waveFrom: what comes out at a point gathers in packs and goes for a target.
Reference
| Part | What it does | Read more |
|---|---|---|
UnitTypeDef | Towers (a launch point for shots), raiders, brutes | Combat |
| Map names | The camp (a point), the gate, the hall they go for | The map editor |
defineComponent, defineTimer, defineListener | Wave state, waves on time, a wave beaten as its last falls | Core engine |
waves.json and a panel | Who comes, how often, for how much gold | Panels |
defineCommand | Call the next wave early for gold | Economy |
defineObjective, objectiveVictory | Hold every wave, keep the hall | Missions |
A component with replicate: 'everyone', client.attach | Each tower's kills, pinned over it | Components |