检测点是否在多边形内C#版本
- 引射线法:从目标点出发引一条射线,看这条射线和多边形所有边的交点数目。如果有奇数个交点,则说明在内部,如果有偶数个交点,则说明在外部
判断一个点是否在多边形内的方法有很多,这里是射线法
在判断的点上画一条水平线,看这条线与多边形的交点,任意一边的点是奇数个,那么该点就在多边形内(因为一条水平线与多边形的交点是偶数个,如果该点在多边形内,那么它的左边或右边相交的点必定是奇数个,所以只要判断一边的情况就行了)
根据两点式可以求出水平线与多边形任意两个相邻点的交点
两点式公式:
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;//点P1和P2形参连线
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;
}