[Unity算法]点是否在多边形范围内

时间:2022-03-23 12:54:44

参考链接:

https://www.zhihu.com/question/26551754

http://www.cnblogs.com/leoin2012/p/6425089.html

原理如下:

[Unity算法]点是否在多边形范围内

代码实现:

 using UnityEngine;
using System.Collections.Generic; public class MathTool { /// <summary>
/// 点是否在多边形范围内
/// </summary>
/// <param name="p">点</param>
/// <param name="vertexs">多边形顶点列表</param>
/// <returns></returns>
public static bool IsPointInPolygon(Vector2 p, List<Vector2> vertexs)
{
int crossNum = ;
int vertexCount = vertexs.Count; for (int i = ; i < vertexCount; i++)
{
Vector2 v1 = vertexs[i];
Vector2 v2 = vertexs[(i + ) % vertexCount]; if (((v1.y <= p.y) && (v2.y > p.y))
|| ((v1.y > p.y) && (v2.y <= p.y)))
{
if (p.x < v1.x + (p.y - v1.y) / (v2.y - v1.y) * (v2.x - v1.x))
{
crossNum += ;
}
}
} if (crossNum % == )
{
return false;
}
else
{
return true;
}
}
}