Unity3D 中判断点与多边形的关系

原文链接:http://www.cnblogs.com/WilliamJiang/p/5632265.html

由点发出的射线与多边形边的交点个数,如果是偶数个说明在多边形的外面,交点个数为奇数个在多边形的内部,下面是代码:

public bool IsPointInPolygon(Vector2 point, Vector2[] polygon)
{
    int polygonLength = polygon.Length, i = 0;
    bool inside = false;
 
 
    float pointX = point.x, pointY = point.y;
 
 
    float startX, startY, endX, endY;
    Vector2 endPoint = polygon[polygonLength - 1];
    endX = endPoint.x;
    endY = endPoint.y;
    while (i < polygonLength) { startX = endX; startY = endY; endPoint = polygon[i++]; endX = endPoint.x; endY = endPoint.y; inside ^= (endY > pointY ^ startY > pointY) 
                  &&
                  ((pointX - endX) < (pointY - endY) * (startX - endX) / (startY - endY));
    }
    return inside;
}

 

转载于:https://www.cnblogs.com/WilliamJiang/p/5632265.html

上一篇:正则表达式


下一篇:C#使用正则表达式匹配富文本内的图片