当前位置:网站首页>Check whether the point is within the polygon

Check whether the point is within the polygon

2022-06-25 08:32:00 Jason? thirteen

Check whether the point is within the polygon C# edition

  • Ray method : Draw a ray from the target point , Look at the number of intersections of this ray and all sides of the polygon . If there are odd intersections , It means inside , If there are even intersections , It means it's outside
    There are many ways to judge whether a point is within a polygon , This is the ray method

 Insert picture description here

Draw a horizontal line on the point of judgment , Look at the intersection of this line and the polygon , The number of points on either side is odd , Then the point is in the polygon ( Because the intersection of a horizontal line and a polygon is an even number , If the point is within the polygon , Then its left or right intersection points must be an odd number , So just judge the situation on one side )

According to the two-point formula, the intersection of the horizontal line and any two adjacent points of the polygon can be obtained

Two point formula :
 Insert picture description here

private bool InArea(Vector2 rPlayerPos, List<Vector3> rPointList)
{
    
    if (rPointList.Count < 3)
        return false;
    int nCrossings = 0;
    for (int i = 0; i < rPointList.Count; i++)
    {
    
        Vector2 rPos1 = new Vector2(rPointList[i].x, rPointList[i].z);
        var bTmpIndex = (i + 1) % rPointList.Count;// spot P1 and P2 Formal parameter connection 
        Vector2 rPos2 = new Vector2(rPointList[bTmpIndex].x, rPointList[bTmpIndex].z);
        if (rPos1.y == rPos2.y)
            continue;
        if (rPlayerPos.y < Mathf.Min(rPos1.y, rPos2.y))
            continue;
        if (rPlayerPos.y >= Mathf.Max(rPos1.y, rPos2.y))
            continue;
        float fX = (rPlayerPos.y - rPos1.y) * (rPos2.x - rPos1.x) / (rPos2.y - rPos1.y) + rPos1.x;
        if (fX > rPlayerPos.x)
            nCrossings++;
    }
    return (nCrossings % 2) == 1;
}
原网站

版权声明
本文为[Jason? thirteen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250716282048.html