1

我正在 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”也使几个列表为空,但不是全部。

4

1 回答 1

0

我也一直在从事自己的游戏项目,并偶然发现了 Clipper 的类似问题。在这种情况下对我有用的不是写这个:

clipper.Execute(ClipType.ctUnion, solution);

...我为 Execute 方法指定了 PolyFillType:

clipper.Execute(ClipType.ctUnion, solution, PolyFillType.pftNonZero, PolyFillType.pftNonZero);

我不确定为什么它对我有用,但我认为这是因为某些路径可以共享公共边缘,因此使用默认的 pftEvenOdd 填充规则它会被删除。

于 2017-08-04T09:09:11.460 回答