首页 > 解决方案 > 无论点数如何,如何在二维网格上形成一个盒子

问题描述

在二维网格上,给定List具有 X 个元素的位置。我如何确保这些元素总是尽可能靠近盒子排列?

即,给定一个包含 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);
}

标签: c#math

解决方案


我最终发现使用总点数的根会起作用。

            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--;
                }
            }

推荐阅读