【发布时间】:2013-06-28 18:08:40
【问题描述】:
我正在制作一个由方块砌成的墙的游戏。墙壁放置在二维网格上,如下所示:
[X][X][X][X]
[ ][X][ ][ ]
[ ][X][ ][ ]
[ ][X][ ][ ]
现在,当我优化碰撞检测时,它有助于将墙数减少到最低限度。在上述情况下,有七个墙块,但如果将这些块组合在一起,则只有两个墙。我很难想出一个最佳解决方案来找到这些组合墙并根据搜索开始的块获得不同的结果(块存储在无序列表中,顺序来自放置它们的顺序编辑)。关于如何解决这个问题的任何想法?它应该是非常基本的东西,但是,你知道,现在是星期五,我不能正常工作。 :)
这是我目前的次优代码,它基本上做了两次检查,水平和垂直“连续性”,然后检查哪一个更好。它还存储“已处理”的墙块,因此它们不会被识别两次,但这当然使它在交叉点变得时髦。
public void CreateCollidersForExport()
{
List<Wall> handledWalls = new List<Wall>();
foreach (Wall w in walls)
{
if (handledWalls.Contains(w)) continue;
handledWalls.Add(w);
// Search how many walls there is horizontally
Vector3 horizontalCenter = new Vector3(w.X, w.Y, w.Z);
List<Wall> tmpWallsHorizontal = new List<Wall>();
tmpWallsHorizontal.Add(w);
foreach (Wall other in walls)
{
if (handledWalls.Contains(other) || tmpWallsHorizontal.Contains(other)) continue;
bool canAdd = false;
foreach (Wall _w in tmpWallsHorizontal)
{
if (other.X == _w.X + Wall.size && other.Y == _w.Y && other.Z == _w.Z)
{
canAdd = true;
horizontalCenter.X += Wall.size / 2;
break;
}
else if (other.X == _w.X - Wall.size && other.Y == _w.Y && other.Z == _w.Z)
{
canAdd = true;
horizontalCenter.X -= Wall.size / 2;
break;
}
}
if (canAdd)
{
tmpWallsHorizontal.Add(other);
}
}
// Search how many walls there is vertically
Vector3 verticalCenter = new Vector3(w.X, w.Y, w.Z);
List<Wall> tmpWallsVertical = new List<Wall>();
tmpWallsVertical.Add(w);
foreach (Wall other in walls)
{
if (handledWalls.Contains(other) || tmpWallsVertical.Contains(other)) continue;
bool canAdd = false;
foreach (Wall _w in tmpWallsVertical)
{
if (other.X == _w.X && other.Y == _w.Y && other.Z == _w.Z + Wall.size)
{
canAdd = true;
verticalCenter.Z += Wall.size / 2;
break;
}
else if (other.X == _w.X && other.Y == _w.Y && other.Z == _w.Z - Wall.size)
{
canAdd = true;
verticalCenter.Z -= Wall.size / 2;
break;
}
}
if (canAdd)
{
tmpWallsVertical.Add(other);
}
}
if (tmpWallsHorizontal.Count > tmpWallsVertical.Count)
{
// tmpWallsHorizontal has the longest "wall" now
}
else if (tmpWallsVertical.Count > tmpWallsHorizontal.Count)
{
// tmpWallsVertical has the longest "wall" now
}
else
{
// Both ways are the same length
}
}
}
【问题讨论】:
-
请向我们展示您的次优代码。
-
这是你想要的输出吗?
(0,0)-(0,3) and (0,1)-(3,1)? -
听起来您必须计算所有可能的组合才能找到最佳组合。如果你最终得到 3 堵墙而不是 2 堵墙,会不会很糟糕?还是两个重叠的?
-
如果墙壁交叉怎么办,那么如果水平墙在第二排怎么办?
-
重叠不是问题,所以它们可以交叉重叠。
标签: c# algorithm optimization