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