Build a building: the process, start to finish
A worker lists the building in builds. The building says how it goes up (construction), how long (buildTime) and what it costs (cost). Its look's construction says what the player sees while it rises.
// in src/rules.ts, in place of the starter's: peasants who build a farm and a barracks
import { constructionFinished, createGame, createMap, defineIds, earn, type GameMap, type IdOf } from '@v12-engine/engine'
export const UNIT = defineIds('peasant', 'farm', 'barracks', 'footman')
export type Unit = IdOf<typeof UNIT>
export const game = createGame({
id: 'my-game',
name: 'My game',
checkView: 'throw',
// what buildings are paid with, and how much each player starts with
resources: [{ id: 'gold', name: 'Gold', start: 600 }],
victory: null
})
game.unit({
id: UNIT.peasant,
name: 'Peasant',
kind: 'unit',
radius: 0.4,
sight: 8,
stats: { health: 220, moveSpeed: 4 },
// what it can build, in the order its card shows them. A unit that builds can also repair
builds: [UNIT.farm, UNIT.barracks]
})
game.unit({
id: UNIT.farm,
name: 'Farm',
kind: 'building',
radius: 1.5,
sight: 6,
// the cells it covers: buildings sit on whole cells
footprint: { w: 3, d: 3 },
// a builder stays and works on it; more builders, faster
construction: 'builder',
// seconds for one builder
buildTime: 20,
// paid when the builder reaches the spot and puts it down
cost: { gold: 80 },
stats: { health: 500 }
})
game.unit({
id: UNIT.barracks,
name: 'Barracks',
kind: 'building',
radius: 1.5,
sight: 8,
footprint: { w: 3, d: 3 },
construction: 'builder',
buildTime: 40,
cost: { gold: 150 },
stats: { health: 900 },
// a finished farm first; then it trains footmen
requires: [UNIT.farm],
trains: [UNIT.footman]
})
game.unit({
id: UNIT.footman,
name: 'Footman',
kind: 'unit',
radius: 0.4,
sight: 8,
stats: { health: 420, moveSpeed: 4 },
cost: { gold: 60 },
buildTime: 12
})
// a reward: 25 gold back each time a farm is finished
game.on(constructionFinished, (world, building) => {
if (building.def.id === UNIT.farm) earn(world.player(building.owner).resources, 'gold', 25)
})
function field(): GameMap {
const map = createMap({ name: 'Field', width: 32, depth: 32, players: 1, game: 'my-game' })
map.players[0].start = { x: 16, z: 16 }
return map
}
game.maps({ field: field() })
game.onStart((world, { map }) => {
// two peasants at each start
for (const player of map?.players ?? []) {
const at = player.start
if (!at) continue
world.spawn(UNIT.peasant, { at, owner: player.id })
world.spawn(UNIT.peasant, { at: { x: at.x + 1, z: at.z }, owner: player.id })
}
})// in src/view.ts, in place of the starter's
import { type GameView, presetView } from '@v12-engine/client'
// the shared art (the starter's assets option); or .glb files of your own in public/models/
import { dungeonKit, rts } from '@v12-engine/assets'
import type { Unit } from './rules'
export const view: GameView<Unit> = presetView({
units: {
looks: {
peasant: {
height: 1.4,
shapes: [{ shape: 'cylinder', size: [0.6, 1, 0.6], offset: [0, 0.5, 0], color: 'team' }]
},
footman: {
height: 1.5,
shapes: [{ shape: 'box', size: [0.7, 1.2, 0.5], offset: [0, 0.6, 0], color: 'team' }]
},
farm: {
height: 2.4,
shapes: [],
// 3 across (the file is 5.5)
model: { src: rts.models.farm, scale: 0.55 },
// a farm that grows out of the ground
construction: {
motion: 'grow',
// sparks off the builder's hand at each blow of its hammer
working: { fx: 'spark-burst', params: { count: 6, size: 0.5 } },
// a puff of dust when it is finished
done: { fx: 'dust' }
}
},
barracks: {
height: 2.2,
shapes: [],
model: { src: rts.models.barracks, scale: 0.93 },
// a barracks in three stages
construction: {
stages: [
// a foundation: a patch of dug earth, dust as it is laid out
{ at: 0, model: { src: rts.models.farmDirt, scale: 0.56 }, fx: 'dust' },
// a frame: bare scaffolding, from a third of the way
{ at: 0.35, model: { src: dungeonKit.models.scaffoldMedium, scale: 0.75 }, fx: 'dust' },
// the building itself from 70% (a stage with no model is the type's own), dust as it appears
{ at: 0.7, fx: 'dust' }
],
// each stage grows up out of the ground with the progress
motion: 'grow',
working: { fx: 'spark-burst', params: { count: 6, size: 0.5 } },
done: { fx: 'dust' }
}
}
}
}
})Done: select a peasant and press Build on its card, then Farm, and click the ground. The peasant walks there, pays 80 gold and the farm appears at a tenth of its health. It grows out of the ground as the peasant hammers, sparks flying, and is done in 20 seconds with a puff of dust; you get 25 gold back. Then build a barracks: dug earth, then scaffolding, then the barracks itself, ready to train footmen once it is done.
How it goes, step by step
| Step | What happens |
|---|---|
| 1. Ordered | The player picks the building on the worker's card and a spot. Nothing is paid yet. |
| 2. Walks there | The worker walks to the spot. Units standing on it are moved aside when it arrives. |
| 3. Checked | The spot must still be free, and what it requires still owned. If not, the player is told why and the order ends. |
| 4. Paid | cost is taken now (the beforeProduce hook may change it, or the time). Not enough: "Not enough gold", and nothing is built. |
| 5. Put down | A site appears at a tenth of its health (production.constructionHealth). constructionStarted is heard. |
| 6. Goes up | Its progress grows each tick a builder works on it, and its health with it. |
| 7. Finished | It stands whole and works. constructionFinished is heard. |
Choose who builds it
construction says how it goes up once it is put down.
import type { UnitTypeDef } from '@v12-engine/engine'
// a builder stays and works on it; the more builders, the faster. When you say nothing
export const farm: Partial<UnitTypeDef> = { construction: 'builder', buildTime: 20 }
// it goes up on its own: the builder is free at once, and nobody can help (as one builder would)
export const ziggurat: Partial<UnitTypeDef> = { construction: 'self', buildTime: 30 }
// it is there whole at once: a wall piece, a ward
export const palisade: Partial<UnitTypeDef> = { construction: 'instant', cost: { gold: 5 } }There is no kind that uses the builder up. The nearest is self: the builder puts it down and walks away.
buildsItself: true is the same as construction: 'self'. buildTime is 1 second when you leave it out.
Let more builders help
Right-click a site with another worker: it joins in. With the engine's rule, the first builder counts whole and every other one half: two builders take two thirds of the time.
import { createGame, type UnitTypeDef } from '@v12-engine/engine'
export const game = createGame({ id: 'my-game', name: 'My game', victory: null })
// every builder counts whole, for every building
game.settings({ production: { buildRate: (_world, _structure, builders) => builders } })
// or for one type: a castle that four builders at most can hurry
export const castle: Partial<UnitTypeDef> = { buildRate: (builders) => Math.min(builders, 4) }Pause it and go on
A site goes up only while someone works on it. Give its builder another order and the site stops where it is. Right-click it with any worker of yours (or an ally's) to go on. A self site never stops.
Cancel it, and get some back
Select the site and press Cancel on its card (or Esc). The player gets back 75% of what they paid, and the site comes down. constructionCancelled is heard, then it dies with the reason cancelled. A site that is destroyed gives nothing back.
import { createGame } from '@v12-engine/engine'
export const game = createGame({ id: 'my-game', name: 'My game', victory: null })
// all of it back on a cancel; sites start at a quarter of their health
game.settings({ production: { cancelRefund: 1, constructionHealth: 0.25 } })Health as it rises
A site starts with a share of its health (production.constructionHealth, a tenth) and gains the rest as it goes up, in step with its progress. Damage taken meanwhile stays: a site hurt on the way is finished hurt, and needs repair.
What a site can and cannot do
Until it is finished, a building:
| Can | Cannot |
|---|---|
| Be attacked and destroyed | Take orders: attack, train, research, upgrade, sell |
| Block the ground it stands on | Give supply (supplyGiven) or take resources in (dropOff) |
| Be seen, and see a little (its radius and 2) | Count for what requires it |
| Be cancelled | Be repaired, or heal by itself |
Where it can go
The worker can put it down only where every cell of its footprint is in the map (not at its edge), dry, not too steep, not blocked, and free of other buildings, on ground level enough across the whole footprint. The player's own preview also says no on ground they have never seen.
Say no to more with the canPlace hook: here, nothing within 10 of an enemy.
import { createGame } from '@v12-engine/engine'
export const game = createGame({ id: 'my-game', name: 'My game', victory: null })
game.before('canPlace', (world, event) => {
// the engine asks without a player too (its own checks): only a player's building is looked at here
if (event.player === undefined) return
const enemies = world.query({ near: { x: event.site.x, z: event.site.z }, radius: 10, of: event.player, is: 'enemy', limit: 1 })
// a reason of your own, which the player is told (its words are in the view)
if (enemies.length) event.cancel({ key: 'mygame.tooCloseToEnemies' })
})import type { GameView } from '@v12-engine/client'
export const view: GameView = {
units: { looks: {} },
hud: { messages: { 'mygame.tooCloseToEnemies': 'Too close to the enemy' } }
}Change its cost or time as it is put down
beforeProduce runs as the worker pays. For a building its kind is structure.
import { createGame } from '@v12-engine/engine'
export const game = createGame({ id: 'my-game', name: 'My game', victory: null })
// a player with three farms or more builds the next ones at half the time
game.before('beforeProduce', (world, event) => {
if (event.kind !== 'structure' || event.id !== 'farm') return
if (world.query({ owner: event.player, type: 'farm' }).length >= 3) event.time /= 2
})Hear when it starts, finishes or is called off
Each is an event: listen with game.on. Here the owner is told each time.
import { constructionCancelled, constructionFinished, constructionStarted, createGame } from '@v12-engine/engine'
export const game = createGame({ id: 'my-game', name: 'My game', victory: null })
game.on(constructionStarted, (world, building) => {
world.message(building.owner, { key: 'mygame.begun', params: { type: building.def.id } }, 'info')
})
game.on(constructionFinished, (world, building) => {
world.message(building.owner, { key: 'mygame.built', params: { type: building.def.id } }, 'info')
})
game.on(constructionCancelled, (world, building) => {
world.message(building.owner, { key: 'mygame.calledOff', params: { type: building.def.id } }, 'hint')
})import type { GameView } from '@v12-engine/client'
// the words, in the view: a param that is a unit type's id is turned into its name
export const view: GameView = {
units: { looks: {} },
hud: {
messages: {
'mygame.begun': (params, registry) => `${registry.unit(String(params.type)).name}: work has begun`,
'mygame.built': (params, registry) => `${registry.unit(String(params.type)).name} is ready`,
'mygame.calledOff': (params, registry) => `${registry.unit(String(params.type)).name} was called off`
}
}
}constructionFinished is heard for an instant building too, as it is put down. A site that is destroyed is heard as entityDied.
Repair it
Right-click a hurt building of yours with a worker. One worker mends all of its health in one and a half times its buildTime, and more workers go faster. It costs 35% of the building's cost for all of its health, paid as the work goes on; when the money runs out, the worker stops. Change the share with game.settings({ economy: { repairCost: 0.5 } }).
Upgrade it into another building
upgradesTo puts a button on its card. The upgrade costs the new type's cost at once, takes its buildTime, and needs what it requires. Meanwhile the building stays what it was: it still gives its supply and counts for what requires it. Cancelling gives all of it back.
import { createGame, defineIds } from '@v12-engine/engine'
export const UNIT = defineIds('hall', 'keep')
export const game = createGame({ id: 'my-game', name: 'My game', victory: null })
// a hall that becomes a keep where it stands
game.unit({ id: UNIT.hall, name: 'Hall', kind: 'building', radius: 2, sight: 10, footprint: { w: 4, d: 4 }, stats: { health: 1500 }, buildTime: 60, upgradesTo: UNIT.keep })
game.unit({ id: UNIT.keep, name: 'Keep', kind: 'building', radius: 2, sight: 12, footprint: { w: 4, d: 4 }, stats: { health: 2000 }, buildTime: 45, cost: { gold: 300 } })morphStarted, morphCancelled and entityMorphed are its events.
Show it going up: how it comes up
motion says how the building rises. grow when you say nothing.
motion | What it does |
|---|---|
grow | Grows up out of the ground, from a fifth of its height |
rise | Rises out of the ground whole, as if pushed up |
fade | Fades in, from nearly see-through |
reveal | Revealed from the ground up by a cut with a glowing edge |
none | Stands as it will be |
A tower revealed by a glowing cut
import type { UnitLook } from '@v12-engine/client'
import { rts } from '@v12-engine/assets'
export const tower: UnitLook = {
height: 3.4,
shapes: [],
model: { src: rts.models.stoneTower, scale: 0.8 },
construction: {
motion: 'reveal',
// the glowing edge: a cold blue, half a unit tall
revealColor: [0.4, 0.7, 1],
revealEdge: 0.5,
// dust as it is laid out
stages: [{ at: 0, fx: 'dust' }],
done: { fx: 'sparkle' }
}
}Scaffolding round it while it rises
Make one model of the building with scaffolding round it, and show it until near the end. Then the finished building takes its place.
import type { ConstructionLook } from '@v12-engine/client'
// as the building's `construction`
export const construction: ConstructionLook = {
stages: [
// your file: the building in its scaffolding (models/barracks/scaffolded.glb), drawn at the type's size. Its roof
// is a node of its own, hidden at first
{ at: 0, model: 'barracks/scaffolded.glb', hide: ['roof'], fx: 'dust' },
// the same model from 60%, its roof on
{ at: 0.6, model: 'barracks/scaffolded.glb', show: ['roof'] },
// the scaffolding comes down: a stage with no model is the finished building. Dust, and a sound of your game's
{ at: 0.9, fx: 'dust', sound: 'scaffold-down' }
],
motion: 'none'
}A stage is drawn with its model, or with the type's own model when it names none. show and hide name nodes of that model; what a later stage shows is hidden until then.
A building that plays its own animation as it is built
A model with a clip of it going up (a "birth" clip) can have that clip follow the progress: at half built, the clip is at its half.
import type { UnitLook } from '@v12-engine/client'
export const forge: UnitLook = {
height: 3,
shapes: [],
// your model, with a clip named Birth (models/forge/forge.glb)
model: { src: 'forge/forge.glb', scale: 1 },
construction: {
clip: 'Birth',
// the clip does the work: no growing on top of it
motion: 'none',
// hammer blows: an effect at the builder's right hand, and a sound of your game's
working: { fx: 'spark-burst', at: 'handslot.r', sound: 'hammer' },
done: { fx: 'dust', sound: 'built' }
}
}A cancelled one, and an upgrade's own look
import type { ConstructionLook } from '@v12-engine/client'
export const construction: ConstructionLook = {
motion: 'rise',
// called off: dust, and it folds into the ground (`fold`, when you say nothing), sinks, or dies a death of its own
cancelled: { fx: 'dust', look: { collapse: { look: 'crumble', pieces: 12 } } },
// the upgrade into another type, by the upgrade's progress: a scaffold round it, then itself
upgrade: {
stages: [
{ at: 0, model: 'hall/upgrading.glb', fx: 'dust' },
{ at: 0.95, fx: 'dust' }
]
}
}An upgrade stands as it is (motion: 'none') unless its look says otherwise.
Full control in code
Give the look a pose. It runs every frame, after the client has placed, turned and sized the building, and is handed where it stands (Placement) to write over; how far it is built is entity.construction (0 to 1, none once it stands), an upgrade's entity.upgrade.
import type { UnitLook } from '@v12-engine/client'
// as the building's `pose`: it rises out of the ground with a shiver, slower at the end
export const pose: UnitLook['pose'] = (entity, place) => {
const progress = entity.construction
if (progress === undefined) return
const eased = 1 - (1 - progress) ** 2
place.y -= (1 - eased) * 3
place.yaw += Math.sin(progress * 80) * 0.01 * (1 - progress)
}GameView.units.constructionFor decides it for every building of the game first: constructionFor: (entity) => (entity.def.race === 'undead' ? { motion: 'fade' } : undefined).
What is data and what is code
| Part | Data | Code only |
|---|---|---|
builds, construction, buildTime, cost, footprint, requires, upgradesTo | yes (data.json, the Data panel) | |
buildRate, game.settings, hooks, events | yes | |
The look's construction as ConstructionLook | yes (looks.json, the Going up tab) | |
The look's pose, GameView.units.constructionFor | yes |
In the editor
- Open Data and pick the building. Set its build time, cost, footprint and how it is built (
construction). Pick the worker and add the building to what itbuilds. Press Keep. - To put a site on the map, place the building from Place (left rail), then turn on Still to be built in the Inspector.
- In Content, right-click the building and pick Look into it. Open Death, damage, icon, portrait, sounds, then the Going up tab.
- Drag Progress to see it at any point. Press Put it up to watch it go up over its build time, and Call it off to see it cancelled.
- Pick how it Comes up: Grows out of the ground, Rises out of it, Fades in, Revealed from the ground up (then Its edge for the colour) or Stands as it will. Pick a Clip to play along with its progress.
- Press A stage from …% to add a stage where the slider is. Set its From, Model, Shows, Hides and Effect.
- Set Working (and the point it plays at), Done and Called off.
- If it upgrades, turn on Its upgrade to set the upgrade's look the same way.
- Every change is written into
looks.jsonat once. As the code's takes it out again.
Reference
Rules (UnitTypeDef)
| Field | Default | What it does |
|---|---|---|
builds | On a worker: the buildings it can put down. It can also repair | |
construction | builder | builder, self or instant |
buildTime | 1 | Seconds for one builder |
buildRate | the game's | (builders, world, structure) => rate: 1 is one builder |
cost | free | Paid as it is put down |
footprint | from radius | { w, d } in cells |
requires | Types the player must have finished first | |
upgradesTo | A type, or types, it can become where it stands |
game.settings | Default | What it does |
|---|---|---|
production.cancelRefund | 0.75 | Share of what was paid back on a cancel |
production.constructionHealth | 0.1 | Share of its health a site starts with |
production.buildRate | first 1, others 0.5 | Speed by builders, for every type |
economy.repairCost | 0.35 | Share of its cost that mending all of its health costs |
| Hook or event | When |
|---|---|
canPlace | A building is about to be placed, and in the player's preview: cancel(reason) |
beforeProduce | It is about to be paid for (kind: 'structure'): change cost, time, or cancel |
constructionStarted | A site was put down |
constructionFinished | It is finished (or put down whole, instant) |
constructionCancelled | Its owner called it off: it dies next, reason cancelled |
worked | A blow of a builder's hammer: { worker, target } |
morphStarted, morphCancelled, entityMorphed | An upgrade began, was called off, was done |
In code: underConstruction(entity) gives a site's progress, buildTime and builders; placementProblem(world, def, point, player) says why a spot is refused; world.spawn(type, { at, owner, underConstruction: true }) puts a site down.
Look (ConstructionLook)
| Field | Default | What it does |
|---|---|---|
motion | grow | grow, rise, fade, reveal, none (none for an upgrade) |
revealColor, revealEdge | warm orange, 0.25 | The glowing edge of reveal |
stages | { at, model, show, hide, fx, point, sound }, each from a share of progress | |
clip | A clip of its model scrubbed by progress | |
working | { fx, at, sound, params } at each builder's blow, at the builder's point | |
done | { fx, sound } as it is finished | |
cancelled | fold | { fx, sound, look }: fold, sink, or a death's look |
upgrade | The same fields, for its upgrade, by the upgrade's progress |
See Add a building for the rest of a building's rules, and Break a building to pieces for how it comes down.