c# - 无论点数如何,如何在二维网格上形成一个盒子
问题描述
在二维网格上,给定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);
}
解决方案
我最终发现使用总点数的根会起作用。
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--;
}
}
推荐阅读
- php - 本地服务器(openserver)上的 $_POST 不起作用
- css - 将标题与卡片对齐
- c - C 程序中的指针
- r - R将文件名附加到列的值
- angular - 一个父组件中的多个 Observable 与每个子组件中的一个 Observable
- testing - 如何判断html视频当前是否正在播放
- django - __init__() 有多个参数值试图覆盖 forms.Form
- python - Selenium Python 按名称查找元素不起作用
- git - 如何从变基中跳过特定文件
- php - 如何在 TFS 中运行 PHP 脚本?在 TFS 中是否可以通过命令行运行 PHP 脚本?