【问题标题】:How to generate a random Vector3 point inside a polygon如何在多边形内生成随机 Vector3 点
【发布时间】:2022-02-12 19:35:03
【问题描述】:

我在 Unity3D 上工作,我有一个 Vector3 数组,这个数组是多边形的顶点。 现在我尝试在多边形内生成一个随机点,但我不知道我有多少个顶点。

例如:

polygonBorders = new Vector3[3];

        polygonBorders[0] = new Vector3(35.3f, 1.3f, -20.1f);
        polygonBorders[1] = new Vector3(35.3f, 1.3f, -3.42f);
        polygonBorders[2] = new Vector3(52.11f, 1.3f, -3.42f);

这是我的多边形,我想要这样的方法:

 Vector3 GeneratePointInsidePolygon(Vector3[] polyogn, Vector3 point)

我尝试在整个互联网上寻找解决方案,但没有解决方案或库

【问题讨论】:

标签: c# unity3d


【解决方案1】:

我找到了一个很好的方法来使用下一个 sn-p:

private Vector3 GeneratePointInsidePolygon(List<Vector3> polygon)
{
    Vector3 MinVec = MinPointOnThePolygon(polygon);
    Vector3 MaxVec = MaxPointOnThePolygon(polygon);
    Vector3 GenVector;
    
    float x = ((Random.value) * (MaxVec.x- MinVec.x)) + MinVec.x;
    float z = ((Random.value) * (MaxVec.z - MinVec.z)) + MinVec.z;
    GenVector = new Vector3(x, groundHight, z);
    
    while(!InConfinedSpace.IsPointInPolygon(polygon,GenVector))
    {
        x = ((Random.value) * (MaxVec.x - MinVec.x)) + MinVec.x;
        z = ((Random.value) * (MaxVec.z - MinVec.z)) + MinVec.z;
        GenVector.x = x;
        GenVector.z = z;
    }
    return GenVector;

}

private Vector3 MinPointOnThePolygon(List<Vector3> polygon)
{
    float minX = polygon[0].x;
    float minZ = polygon[0].z;
    for (int i = 1; i<polygon.Count;i++)
    {
        if(minX > polygon[i].x)
        {
            minX = polygon[i].x;
        }
        if (minZ > polygon[i].z)
        {
            minZ = polygon[i].z;
        }
    }
    return new Vector3(minX, groundHight, minZ);
}

private Vector3 MaxPointOnThePolygon(List<Vector3> polygon)
{
    float maxX = polygon[0].x;
    float maxZ = polygon[0].z;
    for (int i = 1; i < polygon.Count; i++)
    {
        if (maxX < polygon[i].x)
        {
            maxX = polygon[i].x;
        }
        if (maxZ < polygon[i].z)
        {
            maxZ = polygon[i].z;
        }
    }
    return new Vector3(maxX, groundHight, maxZ);
}

private bool IsPointInPolygon(List<Vector3> polygon, Vector3 point)
{
    bool isInside = false;
    for (int i = 0, j = polygon.Count - 1; i < polygon.Count; j = i++)
    {
        if (((polygon[i].x > point.x) != (polygon[j].x > point.x)) &&
        (point.z < (polygon[j].z - polygon[i].z) * (point.x - polygon[i].x) / (polygon[j].x - polygon[i].x) + polygon[i].z))
        {
            isInside = !isInside;
        }
    }
    return isInside;
}

sn-p 找到最小和最大的多边形顶点,然后在里面生成一个随机数,每次检查该点是否在多边形内,如果不是,则生成另一个点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2017-11-20
    • 2021-02-13
    相关资源
    最近更新 更多