Skip to content

Combat and targeting ​

How units pick targets, surround them, wait their turn, and swing. Every default here can be changed with a rule, a hook or code. Everything is exported from @v12-engine/engine.

Quick start ​

ts
export const crossbowman: UnitTypeDef = {
	// ...
	stats: { attackDamage: 14, attackSpeed: 0.8, attackRange: 6 },
	// 0.5 s windup to the bolt, then 0.3 s where it cannot move: no kiting it
	attacks: [{ damagePoint: 0.5, recovery: 0.3, acquisitionRange: 8, projectileSpeed: 20 }]
}

The crossbowman looks for enemies within 8, shoots a bolt that flies at 20 cells a second, and stands still for 0.3 s after each shot.

Common tasks ​

Give a unit two weapons ​

A unit uses the first attack whose targets reach the target. Give the second weapon its own stats so upgrades can change it alone.

ts
export const rules: Rules = {
	stats: [
		{ id: 'bowDamage', name: 'Bow damage' },
		{ id: 'bowSpeed', name: 'Bow speed', format: 'decimal' },
		{ id: 'bowRange', name: 'Bow range', format: 'decimal' }
	],
	units: [
		{
			id: 'huntress',
			// …
			stats: { health: 600, attackDamage: 18, attackSpeed: 1, attackRange: 0.5, bowDamage: 12, bowSpeed: 1.5, bowRange: 6 },
			attacks: [
				{ damagePoint: 0.4, acquisitionRange: 8 }, // the glaive, for what walks
				{ damagePoint: 0.3, acquisitionRange: 9, projectileSpeed: 24, targets: ['air'], stats: { damage: 'bowDamage', speed: 'bowSpeed', range: 'bowRange' } }
			]
		}
	]
}

Give an attack a minimum range ​

ts
attacks: [{ minRange: 3, damagePoint: 1, splash: 2 }] // a catapult cannot hit its own feet

A unit left alone skips targets inside the dead zone; one told to attack steps back out of it first.

Shoot while moving ​

ts
attacks: [{ onTheMove: true, damagePoint: 0.2, acquisitionRange: 7 }] // a horse archer

Focus fire on the weakest ​

ts
world.hooks.add(
	defineHook({
		hook: 'targetScore',
		id: 'mygame.focus',
		run: (_world, event) => void (event.score += (1 - event.target.health / event.target.maxHealth) * 2000)
	})
)

Attack from behind ​

ts
world.hooks.add(
	defineHook({
		hook: 'approach',
		id: 'mygame.backstab',
		run: (_world, event) => {
			if (event.attacker.def.id !== 'assassin') return
			const behind = event.target.facing + Math.PI
			event.point = { x: event.target.pos.x + Math.sin(behind), z: event.target.pos.z + Math.cos(behind) }
		}
	})
)

Limit how many units can hit a hero, or never give up a chase ​

ts
settings: {
	combat: {
		engageLayer: (world, attacker) => (attacker.def.id === 'catapult' ? 'siege' : defaultEngageLayer(world, attacker)), // siege never crowds infantry
		engageRoom: (world, target, attacker) => (target.hero ? 4 : defaultEngageRoom(world, target, attacker)),
		giveUpChase: (_world, attacker) => (attacker.def.id === 'knight' ? Infinity : 1)
	}
}

Add stances (aggressive, defensive, hold fire, no attack) ​

ts
import { type Rules, stancesPack } from '@v12-engine/engine'
import { stanceButtons } from '@v12-engine/client'

export const rules: Rules = { ...game, packs: [stancesPack()] }
export const view: GameView = { ...myView, hud: { cardButtons: stanceButtons() } }

Buttons appear on the command card (keys G, V, X, Z). Stop is not a stance: it cancels the current order, and the unit fights what comes near again.

Give units veterancy ranks ​

ts
import { type Rules, veterancyPack } from '@v12-engine/engine'
import { veterancyMark } from '@v12-engine/client'

export const rules: Rules = {
	...game,
	packs: [
		veterancyPack({
			ranks: [{ name: 'Veteran', xp: 60, stats: { stats: { armor: 2 } } }],
			earns: (world, unit) => unit.def.id !== 'peasant',
			worth: (world, dead) => (dead.isStructure ? 0 : 20)
		})
	]
}
const plate: UnitHudPlate = { items: [veterancyMark(), { bar: 'health' }] } // a chevron per rank on the unit's plate

Left out, the ranks are VETERANCY_RANKS: Veteran at 50 xp, Elite at 150, Heroic at 300 (+10%, 20%, 30% damage and health). grantVeterancy(world, unit, xp) gives xp from your own rules.

Stop idle allies from joining a fight ​

ts
settings: { combat: { helpRange: () => 0 } }

By default, when a unit is hit, idle units of the same owner within combat.helpRange attack the attacker.

Let an order cancel the recovery ​

ts
settings: { combat: { recoveryCancels: () => true } }

Change the fog of war ​

ts
settings: { fog: { explored: 'nothing', mask: 'black', startExplored: false } }

Editor ​

  1. Open the Data panel and pick a unit type.
  2. Each attack's fields are under their own heading (attacks 2 for the second).
  3. In Model Setup, the attack clip's timing is shown against the windup and recovery; set one from the other.
  4. For a map, Map › Starts explored overrides the game's startExplored.

Reference ​

How a crowd fights ​

IdeaWhat happens
EngagedAn attacker fighting or closing in on a target is engaged with it from the tick it picks it (combat.engaged)
LayersAttackers count apart by layer: ground, air, water, or your own. Flyers don't crowd swords
RingsWithin a layer, by reach in bands 1.5 wide: swords, short bows and long guns each have their own ring
RoomA target has room for as many as stand side by side on that ring (about eight swords round a footman)
SpotsGround and water attackers on a unit take a free angle on their ring (combat.slot), so the crowd wraps around
Full targetsA target with no room scores 1000 less, so a free one comes first
Giving upA self-picked chase that gets no closer for giveUpChase is dropped and shunned for SHUN_TIME (4 s). An ordered target is never dropped
WaitingAn ordered attacker with no room waits behind the fighters on its side (combat.queueDistance), hits what comes in reach, and goes in when a spot frees
JamsAn attack-move stuck in a crowd keeps trying while a path exists

The state (combat.engaged, combat.slot, combat.shunned, an order's waiting, meanwhile and spot) is plain data and saved.

Combat rules (Rules.settings.combat) ​

RuleDefaultWhat it says
engageLayer(world, attacker)air for flyers, water for naval, else ground (defaultEngageLayer)The layer it fights from
engageRoom(world, target, attacker)Side by side round the target at the attacker's reach (defaultEngageRoom)How many like it may fight at once
giveUpChase(world, attacker, target)1 sHow long a self-picked chase may stall
queueDistance(world, attacker, target)Target size + two attacker sizes + reach + half a cell (defaultQueueDistance)Where it waits for room
acquisitionRange(world, entity)The farthest acquisitionRange of its attacksHow far it looks for a fight
pickAttack(world, attacker, target)The first attack that reaches (defaultPickAttack)Which attack, by index; -1 for none
recoveryCancels(world, entity)falseWhether an order cuts the recovery short
helpRange(world, helper, victim)The helper's acquisition range and 4How far idle allies come to help; 0 never
damageScale(type, target, source)The incomingDamage and outgoingDamage stats, never below none (damageScale)By how much damage is more or less after armor
healingScale(target, source)The incomingHealing stat (healingScale)By how much healing is more or less
cleave(world, attacker, target, weapon)The attack's and the buffs' cleave, the larger part (cleaveOf)What a melee blow cleaves
attackModifiers(world, attacker, target, modifiers)One of a slot goes off, by priority (bySlot)Which onHit passives an attack sets off (Slots)

movement.makesWay decides which allies step aside: see Movement.

Hooks ​

HookAskedChange
targetScoreFor every enemy a unit could pick, with distance, engaged, roomscore; highest wins; -Infinity rules it out
approachWhere an attacker fights a target from, with the engine's pointpoint
canAttackWhether a unit may attack a targetUsed by stances
beforeAttackBefore a swing, with its weapon

Attack fields (AttackDef) ​

FieldWhat it does
targetsWhat it can hit: the ground, the air, kinds you name
stats{ damage, speed, range }: stats of your own in place of attackDamage, attackSpeed, attackRange
damageTypeIts damage type
damagePointWindup seconds before the blow (shorter at higher attack speed)
recoverySeconds held still after the blow (none by default)
projectileSpeedSpeed of its missile; none for melee
splashRadius of area damage
acquisitionRangeHow far it looks for targets
minRangeDead zone, edge to edge
onTheMoveFires while moving
cleave{ part, radius, angle? }: a melee blow strikes the enemies round its target too (Cleave)
howHow what it kills dies, for the screen

Timing. The windup is cancelled by a new order, a stun or the target vanishing: no blow, no time back (swingCancelled event; players see attackCancelled). The blow fires attackStarted then damaged. The period is always 1 / attackSpeed, and the cooldown runs while walking, which is what makes kiting work; a recovery stops it. A unit swings one weapon at a time (CombatState.weapon). The model's attack clip is fitted around its hit mark (ModelDef.clips[name].marks; two fifths in without one).

Functions ​

CallAnswers / does
pickAttack(world, attacker, target)The attack it would use
rangeAgainst(world, attacker, target)How far that attack reaches
attackStat(stats, attack, 'damage')An attack's number from the stats
farthestReach(def, stats), farthestAcquisition(def)The farthest of its attacks
groundAttack(def)The attack used to attack the ground
tooNear(attacker, target, weapon)Whether the target is in the dead zone
attackTiming(world, entity, weapon){ swing, period, recovery } now
swingTiming(damagePoint, base, speed, recovery)The same from numbers
fireOnTheMove(world, entity, current, dt)One tick of firing on the move, for your own order
attackersOf(world, target, layer?)Everyone fighting it or closing in
engagedWith(world, attacker)What it is fighting
engagedLike(world, target, attacker)How many like it the target has
roomFor(world, target, attacker)How many like it the target has room for
isCrowded(world, target, attacker)Whether there is no room left for it
engageLayer(world, attacker), bandOf(world, attacker)Its layer, and its ring (0 is melee)
spotFor(world, attacker, target)Where it fights from, the approach hook included
freeSpot(world, attacker, target, straight?)A free place now, or none
queuePoint(world, attacker, target, angle?)Where it waits
isBlocked(world, attacker, target), isShunned(world, attacker, target)Chase stalled; target shunned for now
engageWith(world, attacker, target)Engages it and gives it a spot (for your own fighting)
holdOff(world, attacker, order, target, dt)One tick of waiting for room; true while holding off (WaitState)
waitBy(world, attacker, order, target)Lets the target go and waits by it
release(attacker, world)Lets go of the target and its spot
shun(world, attacker, target, seconds?)Leaves the target alone for a while
ts
// a boss that calls for help once it is surrounded
if (attackersOf(world, boss, 'ground').length >= roomFor(world, boss, someSword)) callGuards(world, boss)

Stances ​

stancesPack({ stances }) adds a stance component (told to its owner, saved), stanceCommand ({ entities, stance }) and canAttack/idle hooks. STANCES are four StanceDefs (acquire: 'any' | 'near' | 'none', pursue, fireBack, returnTo):

StanceWhat it does
aggressiveAttacks what it sees and chases it (the engine's default)
defensiveFires at what its attack reaches, keeps its place, walks back
hold fireFires back at whoever hits it
no attackIgnores everyone

An attack order works in any stance. stanceOf(entity) reads it; stanceBadge(entity) is a plate badge. The melee brain's squads use stances where the game has them.

Helping an ally ​

When a unit is hit (damaged), every idle unit of the same owner within combat.helpRange takes the attacker, lowest id first, at most once every three seconds per attacker (CombatState.helpedAt). Units with a player's order, CombatState.passive, no attack, already fighting, asleep, or unable to see or attack it do not help; canAttack and targetScore have the last word. Creeps use their camp's own rule instead (Creeps).

Veterancy ​

veterancy component ({ xp, rank }, everyone sees it, saved), rankedUp event, rankOf(unit, ranks), veterancyRank(unit) on the screen, veterancyMark({ color, size, ranks }) for a plate. Kills give what they would give a hero (xpWorth).

Fog (RuleSettings.fog, FogSettings) ​

FieldDefaultWhat it does
explored'remembered'Seen ground stays dim with buildings as last seen; 'nothing' forgets
startExploredfalseWhole map explored at the start, neutral things seen (TeamMemory.startKnown); a map can override (MapDef.explored)
mask'black'Never-seen ground is black; 'dim' for dim

The screen reads fogBrightnessOf(settings.fog), with your view's own over it (GameView.world.fog, client.setFog). The debug panel's Map explored (the fog stays) toggles exploring for everyone (exploreCommand.make({ on })).