Skip to content

Movement and formations ​

How units walk past each other, through trees and over slow ground, and how a group sent to a point lays itself out. Everything is exported from @v12-engine/engine; the player's side is in @v12-engine/client.

Quick start ​

ts
// a group that arrives together, in a ring around the point
world.issue({ type: 'order', player: 1, entities: ids, order: { type: 'move', point: { x: 40, z: 60 }, together: true, formation: 'circle' } })

The units walk at the pace of the slowest and each takes its own place on a ring around the point.

Common tasks ​

Make right-click moves keep the group together ​

ts
settings: { movement: { together: true, formation: () => 'rows' } }

Add a formation of your own ​

ts
// a column: one behind the other
const column: FormationDef = {
	id: 'column',
	name: 'Column',
	shape: (count, spacing) => Array.from({ length: count }, (_, i) => ({ x: 0, z: -i * spacing }))
}

// a wedge, the hero at its tip
const wedge: FormationDef = {
	id: 'wedge',
	name: 'Wedge',
	points({ units, target, spacing, place }) {
		const points = new Map<EntityId, Vec2>()
		const rest = units.filter((unit) => !unit.hero)
		for (const hero of units.filter((unit) => unit.hero)) points.set(hero.id, target)
		rest.forEach((unit, i) => points.set(unit.id, place((i % 2 ? 1 : -1) * Math.ceil((i + 1) / 2) * spacing, -Math.ceil((i + 1) / 2) * spacing)))
		return points
	}
}

export const myGame: Rules = {
	// ...
	formations: [column, wedge],
	settings: { movement: { formation: (_world, units) => (units.some((unit) => unit.hero) ? 'wedge' : 'rows') } }
}

A shape gives places in the formation's own space (x right, z forward, the front first) and the engine fits units to them. points places each unit by id yourself. A formation with an engine id replaces it.

Let the player pick a formation ​

ts
client.controller.setFormation('wedge') // every order to a point now carries it; undefined for the rules' default

A right-click held on the ground shows a ring where each unit will stand, until it is let go. Ctrl with it (order.circle, the player's to rebind) makes that one order a circle, whatever the formation chosen: pressed or let go while the button is held, the rings change with it. Dragged, the right-click turns the formation (as in AoE4): rings show where each unit will stand, and the order is sent with that facing. controller.formationGhosts(point, facing) gives the places for your own drawing.

Make mud slow units and roads speed them up ​

ts
export const tiles = [...presetTiles, defineTile({ id: 'mud', name: 'Mud', speed: 0.5 })]
export const cellLayers = [defineCellLayer({ id: 'swamp', name: 'Swamp', speed: 0.6 })]
// or value by value: a style of grass (`foliage.speed`) in place of the layer's speed
export const grass = defineCellLayer({ id: 'grass', name: 'Grass', values: [{ value: 1, name: 'Thicket', foliage: { speed: 0.7 } }] })

Paths weigh slow ground too, so units take the road round the mud where it is quicker. Flyers and boats are not slowed. A style of grass with walkable: false is gone round as a wall (Grass and bushes).

Speed a unit by where it stands, in code ​

ts
settings: { movement: { moveSpeed: (world, entity, speed) => speed * groundSpeedAt(world, entity) * (onRoad(entity) ? 1.2 : 1) } }

Multiply by groundSpeedAt to keep the ground's own effect.

Stop units stepping aside, or make cavalry always go round ​

ts
settings: {
	movement: {
		// cavalry never squeezes through: round, however long
		goesAround: (world, mover, around, longer, straight) =>
			mover.def.id === 'knight' || defaultSettings.movement.goesAround(world, mover, around, longer, straight),
		// nobody steps aside for a peasant
		makesWay: (world, mover, other) => mover.def.id !== 'peasant' && defaultSettings.movement.makesWay(world, mover, other)
	}
}

A guard that never leaves its post ​

ts
world.hooks.add(
	defineHook({
		hook: 'makeWay',
		id: 'mygame.posts',
		run: (_world, event) => {
			if (event.other.orders[0]?.type === 'guard') event.point = null
		}
	})
)

Tune crowd steering ​

ts
navigation: { separation: 0.5, avoidance: 'low', radii: 'auto', walls: 'soft' }

Editor ​

  1. View › Slow ground tints the cells that slow units.
  2. The Terrain panel shows a tile's speed beside its name.
  3. Play here pushes the map's heights, cliffs and water into the running game; the paths are recut at once.

Reference ​

How a unit gets past others ​

  1. It looks ahead lookAhead cells (3) for units standing still in its way, a knot counted as a whole.
  2. It goes round where the way round is not much longer (movement.goesAround: up to 1.5 more plus a quarter of the straight way).
  3. Otherwise it asks allies that make way (movement.makesWay: idle allies and allies waiting by a fight) to step aside before it gets there. Each steps to where nobody stands, where there is such a place; one held up on its step asks those in its way in turn, three deep at most, so that a crowd parts without the whole of it moving.
  4. Held up 3 seconds, it tries again (MovementState.tries): sent on anew, it looks round the whole knot, however big, and goes round it however long the way (whatever movement.goesAround says), or asks those in it aside. Enemies, or units on their way, are waited out the same way. It gives up (failed, stuck) after 4 tries, 15 seconds held up in all, its tries counted again whenever it gets 2 cells nearer; at once where what holds it up is the ground (the end of its path short of the point: a wood, a cliff) or units holding their ground (anchored).

A unit walking past four standing footmen keeps about 96% of its speed. One sent out through 100 footmen standing 1.25 apart gets there (it gave up about one trip in twenty).

When a unit is there ​

  • At its point, within range (0.2 for a move).
  • Near enough, where another stands on the point (or is on its way to that very point and there already): held up 0.6 seconds within 1.25, or 3 seconds within 3. Several sent to one point stand round it rather than jostle for ever.
  • Not short of a point nobody stands on: it asks those in the way aside, and tries again, as above. Out of tries within 3 cells, it stops there (arrived); further off, failed.

Movement rules (Rules.settings.movement) ​

RuleDefaultWhat it says
lookAhead(world, mover)3How far ahead it looks; 0 only at its nose
goesAround(world, mover, around, longer, straight)longer <= 1.5 + straight * 0.25Whether it goes round the knot
makesWay(world, mover, other)Idle allies, and allies waiting by a fightWhether an ally steps aside
moveSpeed(world, entity, speed)Speed × the ground'sSpeed where it is
togetherfalseRight-click moves of a group go at the slowest one's pace
formationrowsThe formation when an order names none

Hooks ​

HookAskedChange
detourA unit is about to go round a knot (around, straight, longer, point)point, or null to go straight through and ask them aside
makeWayAn ally is about to be asked aside (mover, other, direction, point)point, or null to leave it standing
formationPlaces are worked out (units, target, formation, points)Any of them

Crowd options (Rules.navigation) ​

OptionDefaultWhat it does
separation0.5How hard walking agents push apart (Detour's own is 1.5); 0 for not at all
avoidance'medium''low', 'medium', 'high' (AVOIDANCE_LEVELS) or weights (AvoidanceParams). 'low' is a quarter cheaper with 1000 walking, and plays differently
radii'auto'Unit sizes the ground is cut for (below); false for one cut at 0.5; a list of radii
walls'soft'Steer against walls only when other agents are near (SOFT_WALLS); 'detour' for Detour's every-tick steering

Several sizes. With 'auto', ground units are grouped by radius (up to 0.5, up to 0.75, over 0.75) and each group with a unit type gets its own navigation, cut for its largest radius. Every unit stands as a mirror in the other sizes' crowds, so big and small push each other properly. Each size costs about 75 ms to build and 74 KB on a 128-cell map (cached by ground hash). Changing this changes the determinism hash.

Between trees. With walls: 'soft', a unit steers only while another agent is within eight radii; otherwise it follows its path. Units go through two-cell gaps at full speed (Detour's steering slowed them to 0.85-0.9). A one-cell gap stays shut.

Formations ​

FormationLayout
rowsA tight group keeps its shape; a scattered one lines up in rows across the way of travel
circleA disc of rings around the point, filled to the middle; up to 12 stand on one ring
squareA filled block, as many across as deep (100 is 10 × 10); a short last row at the back
noneEveryone to the point itself

Each in its place. Those of a formation (MovementState.formation, the order's group) keep the place they get to (MovementState.place), and settle into a whole shape:

  1. Held up by one of them at its place, on the way further in, the one standing goes on to the place further in and the one held up takes the place it leaves (a ring deep in a circle fills through those that came first, a step at a time). The one standing has to be at least 0.25 nearer the place.
  2. Its place taken by one of them off its own, they swap places.
  3. Held up by one of them on its way too, they trade places where the two ways together are at least 0.5 shorter (they met head on, or crossed).
  4. By its place, the gap narrowed by those either side, they step 0.4 away to let it in; an ally of none of it standing on the place is asked aside.
  5. Stepped aside or pushed off its place, a unit walks back once it has stood off it 0.75 seconds, as one of the formation (the rules above hold on the way), and stops where it is when held up 3 seconds near it. Where one of the formation stands on its place, off its own, that one keeps it and the walker goes to the other's. It lets the place go after 5 walks back without getting there, so that nothing jostles for ever. A move of its own, or another order, lets it go too.

Those of a formation never step aside for each other. 20 to 150 footmen in a circle, square or rows, from ranks, scattered or another formation, stand each within 0.35 of a place of its own, every place taken, in 8 to 15 seconds on average for 22 cells (tests/crowdMoves.test.ts).

Walkers and flyers are laid out apart; each place is snapped to standable ground. Spacing is twice the biggest radius plus FORMATION_GAP. OrderInit.facing turns the formation (0 is +z). together: true caps everyone at the slowest one's speed for the move (OrderParams.speedCap, MovementState.cap); attack-moves always go at their own speed.

CallWhat it does
formationPoints(world, units, target, formation, facing?)The places, for your own order
formationPreview(registry, units, target, navs, formationId, facing)The same from what a player's screen knows
GameSession.formationPlaces(units, point, facing, formation)The same, over a session (works over a wire)
fitToPlacesFits units to a shape's places with the fewest crossings
world.registry.formation(id), world.registry.formationsFind them
rowsFormation, circleFormation, squareFormation, noneFormation, coreFormationsThe engine's own

FormationContext has the group's middle, the way of travel, place(x, z), snap and turned. The debug panel has a Formation list (client.debugTools.choices).

Moving units in code ​

CallWhat it does
moveTo, moveToEntity, halt, faceTowardsWhat orders move units with; moveTo takes aside: true
setAnchored, setGhostPin a unit, or let others walk through it
standsInWay(world, mover, other)Whether another unit is in the way
stepAside(world, mover, other, direction, agent)Ask one aside; makeWay(world, mover) asks everyone at its nose
lookAhead(world, entity, agent)The look ahead, for your own movement system
groundSpeedAt(world, entity), groundSpeedOfCell(world, x, z)The ground's speed factor

entity.get(moving) has detour, detourAim, slowTime and aside. AgentState.nx, nz (Navigation.readAgent) is the corner after the next. A slowing layer painted in play (world.setCells) recuts the navigation's tiles it reaches, so the paths part where it does, exactly as in a world loaded from a save made afterwards (under a millisecond for a 10 × 10 patch, about a third of a millisecond a tile a unit size on a large paint; never the whole navigation, whose cut costs twice as much as all its tiles one by one); a layer with a thicket among its styles recuts the tiles beside the painted ones too, where the ground units keep from a thicket reaches over a tile's edge; world.reshapeGround recuts the paths where the patch reaches (Navigation.reshape): only the navigation's tiles under it, or all of them where the ground's bounds moved (its edge flooded or raised past the rest). The paints and reshapes of one tick are recut together, each tile once, as the tick ends, or before that as soon as anything asks the navigation (a path, a unit put down), so that nothing finds its way on the ground as it was. A paint made during a tick reaches the navigation with the tick's events, as the tick ends, so what asks the navigation later in that tick still finds the ground as it was before the paint; a reshape reaches it at once.

Walk while facing a unit ​

A move with faces keeps the unit turned to that unit all the way: it backs off, or steps sideways, facing it. A brain giving ground does this; so does a shield-bearer's system that sets MovementState.faces on its walks.

ts
world.issue({ type: 'order', player: 1, entities: [archer.id], order: { type: 'move', point: away, faces: boss.id } })

On the screen, locomotion in @v12-engine/client picks a forward, back, left or right clip from the way the unit goes against the way it faces.