我正在 Unity 中创建一个 2D 游戏,它具有程序放置的图块。我想使用 Angus Johnson 的 Clipper 库(特别是联合函数)来简化碰撞几何,但我遇到了库返回空解决方案的问题,我不知道为什么。
这是我用来组合几何的函数的简化版本:
List<List<Vector2>> unitedPolygons = new List<List<Vector2>>();
Clipper clipper = new Clipper();
Paths solution = new Paths();
ClipperOffset offset = new ClipperOffset();
//Use a scaling factor for floats and convert the Polygon Colliders' points to Clipper's desired format
int scalingFactor = 10000;
for (int i = 0; i < polygons.Count; i++)
{
Path allPolygonsPath = new Path(polygons[i].points.Length);
for (int j = 0; j < polygons[i].points.Length; j++)
{
allPolygonsPath.Add(new IntPoint(Mathf.Floor(polygons[i].points[j].x * scalingFactor), Mathf.Floor(polygons[i].points[j].y * scalingFactor)));
}
bool succeeded = clipper.AddPath(allPolygonsPath, PolyType.ptSubject, true);
}
//Execute the union
bool success = clipper.Execute(ClipType.ctUnion, solution);
Debug.Log("Polygons after union: " + solution.Count);
//Offset the polygons
offset.AddPaths(solution, JoinType.jtMiter, EndType.etClosedPolygon);
offset.Execute(ref solution, 5f);
//Convert back to a format Unity can use
foreach (Path path in solution)
{
List<Vector2> unitedPolygon = new List<Vector2>();
foreach (IntPoint point in path)
{
unitedPolygon.Add(new Vector2(point.X / (float)scalingFactor, point.Y / (float)scalingFactor));
}
unitedPolygons.Add(unitedPolygon);
}
return unitedPolygons;
我通过调试发现的是第一个 Execute (用于联合)返回一个空的解决方案。我发现“Clipper”类中的“BuildResult”函数确实在运行,并且“m_PolyOuts”中有数据,但该列表中“OutRec”的“Pts”属性全部为空。我无法弄清楚这种情况发生在哪里,或者它们是否一开始就被设置了。
我确信这是正确的行为,我只是错误地使用了库,但我找不到任何文档或示例来解释我需要更改哪些内容才能使联合成功。
谢谢。
编辑:我把它缩小了一点。在 Clipper 类的“ExecuteInteral”期间,“Pts”列表不为空,直到“FixupOutPolygon”函数运行。之后,所有列表都为空。“JoinCommonEdges”也使几个列表为空,但不是全部。