簡體   English   中英

在C#中對Clipper感到困惑

[英]Confused on Clipper in C#

我正在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”還使幾個列表為空,但不是全部。

我也一直在從事自己的游戲項目,偶然發現Clipper存在類似問題。 在這種情況下對我有用的是代替編寫此代碼:

clipper.Execute(ClipType.ctUnion, solution);

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

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

我不確定為什么它對我有用,但是我認為這是由於某些路徑可以共享公共邊,因此使用默認的pftEvenOdd填充規則,它會被刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM