Sending every selected unit to the clicked point puts them all on the same spot, and giving them formation spots in array order makes their paths cross. In our Godot 4.7 test of 500 random moves of 9 units, the clicked point left them 0.00 m apart, and spots in array order crossed paths 15.23 times per move, with two units closer than 0.5 m on the way in every move. Matching spots to the group's own left-right and front-back order and slowing the units with shorter walks so that all arrive together kept every pair at least 0.94 m apart, in all 500 moves.
The code
Save it as formation_slots.gd and load it with const Formation := preload("res://formation_slots.gd"). When the player gives a move order, call var spots := Formation.assign(positions, clicked_point) with the selected units' positions, then var speeds := Formation.speeds(positions, spots, 4.0), and send unit i to spots[i] at speeds[i]. The spots are rows 1.5 m apart facing the way the group moves; change the spacing for bigger units. We tested straight walks on open ground. With a NavigationAgent3D, set each unit's target position to its spot and cap its speed the same way.
extends RefCounted
## Gives every unit in a selected group its own spot around the clicked point,
## in rows facing the way the group moves, and a walking speed so that they all
## arrive at the same moment without walking through each other.
## const Formation := preload("res://formation_slots.gd")
## var spots := Formation.assign(positions, clicked_point)
## var speeds := Formation.speeds(positions, spots, 4.0)
## for i in units.size(): units[i].go(spots[i], speeds[i])
static func slots(count: int, target: Vector3, forward: Vector3, spacing := 1.5) -> Array[Vector3]:
forward.y = 0.0
forward = forward.normalized() if forward.length() > 0.001 else Vector3.FORWARD
var right := forward.cross(Vector3.UP)
var cols := ceili(sqrt(count))
var rows := ceili(float(count) / cols)
var out: Array[Vector3] = []
for i in count:
var row := i / cols
var in_row := mini(cols, count - row * cols)
var x := ((i % cols) - (in_row - 1) * 0.5) * spacing
var z := ((rows - 1) * 0.5 - row) * spacing # row 0 is the front row
out.append(target + right * x + forward * z)
return out
static func assign(positions: Array[Vector3], target: Vector3, spacing := 1.5) -> Array[Vector3]:
var n := positions.size()
if n == 0:
return []
var center := Vector3.ZERO
for p in positions:
center += p
center /= n
var spots := slots(n, target, target - center, spacing)
var pick: Array[int] = []
for i in n:
pick.append(i)
# swap two units' spots when the unit further left (or behind) was given the
# spot further right (or ahead): this keeps the group's shape in order
var changed := true
while changed:
changed = false
for i in n:
for j in range(i + 1, n):
if (positions[i] - positions[j]).dot(spots[pick[i]] - spots[pick[j]]) < -0.0001:
var k := pick[i]
pick[i] = pick[j]
pick[j] = k
changed = true
var out: Array[Vector3] = []
for i in n:
out.append(spots[pick[i]])
return out
static func speeds(positions: Array[Vector3], spots: Array[Vector3], max_speed: float) -> Array[float]:
# the unit with the longest walk goes at max_speed, the others slower,
# so that everyone arrives at the same moment
var longest := 0.001
for i in positions.size():
longest = maxf(longest, positions[i].distance_to(spots[i]))
var out: Array[float] = []
for i in positions.size():
out.append(max_speed * positions[i].distance_to(spots[i]) / longest)
return out
What we measured
500 move orders for 9 units and 300 for 16 units, each from a loose group in a 7 by 7 m area with units at least 1.2 m apart, to a point 12 to 25 m away in a random direction. Units walk at up to 4 m/s and positions were checked 30 times a second, without physics bodies. The random moves come from a fixed seed, and two runs gave the same numbers.
- Everyone to the clicked point: all units ended on the same spot, 0.00 m apart, in every move.
- Formation spots in array order: paths crossed 15.23 times per move on average, up to 30 (52.80 and up to 88 with 16 units), and two units came closer than 0.5 m in every move.
- Spots matched by the script, but everyone at 4 m/s: 2.86 crossings per move, but two units still came closer than 0.5 m in 213 of 500 moves (191 of 300 with 16), because the units that arrive first stand in the way of the ones still walking.
- Spots matched by the script and walked at its speeds: no two units came closer than 0.5 m in any move. The closest pair in a move was 1.22 m apart in the middle move and 0.94 m in the worst one (1.12 m and 0.95 m with 16 units). Every unit ended on its own spot, 1.50 m from its neighbours, and the whole group was there after 5.13 s on average, against 5.63 s for spots in array order.
Why it happens
Spots handed out in array order ignore where each unit stands, so the unit on the left side of the group is often sent to the right side of the formation. The script swaps any two units whose spots are the wrong way round compared with where they stand, which keeps the group's order. When everyone also covers the same share of their walk at the same time, the gap between two units is always a mix of their gap at the start and their gap at the end, and with starting gaps of at least 1.2 m and spots 1.5 m apart it cannot drop below about 0.94 m. Paths can still cross on a map, 2.86 times per move with 9 units, but never with both units at the crossing at the same moment. The cost is that the unit with the longest walk sets the pace and the units close to their spots walk slowly.
What to change
- Picking the units first: a drag-select box for 3D units.
- Units that chase a moving target instead of a spot: keep a horde from merging into one blob.
- A unit that should stop on its spot without shaking: move_toward instead of overshooting.
What the orders look like: Medieval Warfare & Siege VFX for Godot 4 has 33 ready-made siege effects in Stylized and Retro PSX looks, including Unit Select rings, Move Order and Attack Order markers, arrow volleys that stick in the ground and a trebuchet.
Tested in Godot 4.7 with the Compatibility renderer.
Ready-made: Medieval Warfare & Siege VFX for Godot 4 has 33 ready-made siege effects in Stylized and Retro PSX looks, including Unit Select rings, Move Order and Attack Order markers, arrow volleys that stick in the ground and a trebuchet.
More how-tos for Medieval Warfare & Siege VFX for Godot 4: Drag a box to select 3D units, in any direction · Hit the target with an arcing shot at any angle and height
More how-tos: Game systems
- Hover a 3D object inside a SubViewport
- A turned building that covers the cells it stands on
- An inventory that never loses an item and never overfills a stack
- A JSON save that loads back exactly what you saved
- Fire that spreads one cell per step, in every direction
- A pooled enemy that comes back as fresh as a new one
- An enemy that stops at the dead player and finds the respawned one
- Poison, burn and bleed that keep ticking when applied again
- XP, qi and gold that keep growing without going negative
- Count slot line wins with wilds in front
- Random directions spread evenly over a sphere or a cone
- Count a lap only when the car really went round
- Make a seed repeat: daily runs, replays and roguelike seeds
- Offline progress that counts the time the game was closed
- A chance roll without the long bad-luck streaks
- Check crafting recipes in any order, with the right counts
- Make HP and mana regen the same at any frame rate
- Damage over time with the right number of ticks
- Spawn enemies where the camera cannot see them
- Keep a chasing horde from stacking into one enemy
- Make the fish bite after the same wait at any frame rate
- Snap buildings to the right grid cell on both sides of the origin
- Make a cooking timer fire once, on time
- Pick from a weighted loot table with the right chances
- Level up as many times as the XP covers
- Walk a patrol guard to each point without overshooting
- Remove items from an Array while checking them, without skipping any
- Scatter spikes, roots or trees in a circle without overlaps
- Count and take crafting items from every stack
- Play random sounds and events without obvious repeats
- Pick the growth image so the ripe one shows exactly when the crop can be picked
- Turn a day counter into season, day and year without a day 0
- An enemy that dies once, however many hits land
- A fair shuffle you can replay
- A ghost that drives the lap at real speed
- A vision cone that does not flicker at the edge
- A sprinkler that waters a round patch
- A slot reel that always lands forward on the result
- A crowd of NPCs that never emote or bob in step
- A song position that moves on every frame
- Nodes your editor tool adds that stay in the scene