Home > Back-end >  How to generate a random Vector3 point inside a polygon
How to generate a random Vector3 point inside a polygon

Time:02-12

I work on Unity3D and I have a Vector3 array, this array is the vertex of a polygon. Now I try to Generate a random point inside the polygon and I don't know how many vertex I have.

e.g:

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);

this is my polygon and I want a method like that:

 Vector3 GeneratePointInsidePolygon(Vector3[] polyogn, Vector3 point)

I try to find a solution all over the Internet and there is no solution or libraey

CodePudding user response:

I find a nice way to do that with the next script:

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;
}

The script find the minimum and maximum polygon vertex and then generate a random number inside and check if the point is inside the polygon every time, if it's not I generate another point.

  • Related