Tactics Game Formation

Godot Version

Godot 4.2

Question

How do I create a formation selection system? I want my soldiers to line up in the formation that the player selects.
Formation

One approach is to store positions for the types in a dictionary with arrays.

Then, for each of the type, you try to match the position to an item in the array.

For example

enum TYPE {COMMANDER, STANDARD_BEARER, SOLDIER}

const square_formation = {
  TYPE.COMMANDER: [Vector2(-20, 0)],
  TYPE.STANDARD_BEARER: [Vector2(20, 0],
  TYPE.SOLDIER: [Vector2(-60, 0), Vector2(0, -60), Vector2(60, 0), Vector2(0, 60)]
}

This specific example is simple and will allow 4 positions for soldiers only, you will want to use more and probably not a const since in addition you are probably going to want to calculate the positions rather than having them static.

But this simplified example will demonstrate the method…
Then when you apply the formation, match the target position for each type of unit to a position in the formation.

In this case, let’s say you have 2 soldiers, 1 commander and 1 standard bearer.

var units_by_type = {}

for unit in selected_units:
  if units_by_type.has_key(unit.type):
    units_by_type[unit.type].append(unit)
  else:
    units_by_type[unit.type] = [unit]

for unit_type in units_by_type:
  var index = 0
  for unit in units_by_type[unit_type]:
    unit.position = square_formation[unit.type][index]

Your commander and standard bearer will now be in the middle, commander 20 px left of origo and the other 20 px right of origo.

Then the 2 soldiers will take position 1 to the left 60px and 2, to the top 60px.

Again, this is a simplified example.