参考链接:
https://www.zhihu.com/question/26551754
http://www.cnblogs.com/leoin2012/p/6425089.html
原理如下:
代码实现:
1 using UnityEngine; 2 using System.Collections.Generic; 3 4 public class MathTool { 5 6 /// <summary> 7 /// 点是否在多边形范围内 8 /// </summary> 9 /// <param name="p">点</param> 10 /// <param name="vertexs">多边形顶点列表</param> 11 /// <returns></returns> 12 public static bool IsPointInPolygon(Vector2 p, List<Vector2> vertexs) 13 { 14 int crossNum = 0; 15 int vertexCount = vertexs.Count; 16 17 for (int i = 0; i < vertexCount; i++) 18 { 19 Vector2 v1 = vertexs[i]; 20 Vector2 v2 = vertexs[(i + 1) % vertexCount]; 21 22 if (((v1.y <= p.y) && (v2.y > p.y)) 23 || ((v1.y > p.y) && (v2.y <= p.y))) 24 { 25 if (p.x < v1.x + (p.y - v1.y) / (v2.y - v1.y) * (v2.x - v1.x)) 26 { 27 crossNum += 1; 28 } 29 } 30 } 31 32 if (crossNum % 2 == 0) 33 { 34 return false; 35 } 36 else 37 { 38 return true; 39 } 40 } 41 }