在二维网格上,给定一个包含X个元素的位置的List
。我如何确保这些元素总是尽可能地排列成一个方框?
。E给定一个包含9个元素的列表,形成如下:
o o o
o x o
o o o
给定一个包含5个元素的列表,形成如下:
o x o
o o
等等
//selection is a list of random positions on the grid, I click on the map and want them to move and form a box formation
Vector2Int origin = mousePosition;
List<Vector2Int> boxPositions = new List<Vector2Int>();
int rows = ?
int cols = ?
for (int i = 0; i < selection.Count; i++)
{
//Calculate position
boxPositions.Add(myNewlyCalculatedPosition);
}
我最终发现,使用总点数的根是可行的。
int total = selection.Count;
int rows = Mathf.CeilToInt(Mathf.Sqrt(total));
for (int x = 0; x < rows; x++)
{
if (total <= 0)
break;
for (int z = 0; z < rows; z++)
{
if (total <= 0)
break;
positions.Add(adjustedWorldPos);
total--;
}
}