C#

// This will compute the number of columns needed to fit all the units in the // squarest rectangle possible. int columnCount = (int)(Math.Ceiling(Math.Sqrt(Entities.Count))); // The number of rows may be less than columns if the number of units is not // an exact square. Also, the last row may be incomplete. int rowCount = (Entities.Count + columnCount - 1) / columnCount; // Figure out the grid size needed (this step is not necessary if all entities // are the same size.) // NOTE: These lines will throw an exception if Entities is empty. int xSize = Entities.Max(e=>e.Size.X); int ySize = Entities.Max(e=>e.Size.Y); // This is the top-left corner of the grid, which is to be centered on // parTarget. Vector2 gridCornerOffset = parTarget + new Vector2(-xSize * columnCount / 2, -ySize * rowCount / 2); // Send each entity to its position at the target. for(int i = 0; i < Entities.Count; ++i) { int gridX = i % columnCount; int gridY = i / columnCount; Vector2 position = gridCornerOffset + new Vector2(xSize * gridX, ySize * gridY); Entities[i].GoToTarget(position); }

EDIT: If you instead want a rectangle formation, you can change the first line to the following:

C#

// This is the width to height ratio of the desired rectangle. double r = 2; // for 2:1 rectangle int columnCount = (int)(Math.Round(r * Math.Sqrt(Entities.Count / r)));