获取顶点列表的周长

Get the perimeter of a list of verticies

我目前正在开发一个关卡编辑器,我已经收集了要用于创建多边形碰撞器的顶点列表。

我通过将某些图块标记为“碰撞器”获得了这些顶点,并且 运行 它们通过算法获得了连接的图块列表。然后我从连接的图块列表中创建了一个顶点列表并删除了所有重复项。

下面是一张有助于解释的图片。所有的点都是当前在我的列表中的顶点,但我想使用红色的点来创建多边形。

这就是我最终解决问题的方式。每个顶点都是四个不同图块的一部分(不包括地图案例的边缘),所以我只是遍历每个顶点并计算有多少个邻居 "of the same type"。如果结果为 4,则表示该顶点位于多边形的中间某处。如果结果为 3,则表示顶点位于内角。 2 意味着它处于优势地位。 1 表示它是外角。

private List<Vector2> GetPerimeterOfVerticeList(List<Vector2> vertices, TileType type)
{
    int neighborCount = 0;
    List<Vector2> perimeter = new List<Vector2>();

    //Check the four tiles touching this vertex
    foreach (Vector2 v in vertices)
    {
        //upper left tile
        if (v.x - 1 >= 0 && v.y <= gridHeight - 1 && grid[(int)v.x - 1, (int)v.y].type == type)
        {
            neighborCount++;
        }
        //upper right
        if (v.x <= gridWidth - 1 && v.y <= gridHeight - 1 && grid[(int)v.x, (int)v.y].type == type)
        {
            neighborCount++;
        }
        //bottom right
        if (v.y - 1 >= 0 && v.x <= gridWidth - 1 && grid[(int)v.x, (int)v.y - 1].type == type)
        {
            neighborCount++;
        }
        //bottom left
        if (v.y - 1 >= 0 && v.x - 1 >= 0 && grid[(int)v.x - 1, (int)v.y - 1].type == type)
        {
            neighborCount++;
        }


        //If we have less than 4 neighbors, it means we are on the edge. 3 is an inner corner, 2 is a side piece, 1 is an outer corner
        if (neighborCount < 4)
        {
            perimeter.Add(v);
        }

        //Reset the neighbor count back to 0 for the next vertex check.
        neighborCount = 0;
    }
    return perimeter;
}