TA的每日心情 | 开心 昨天 06:36 |
---|
签到天数: 15 天 [LV.4]偶尔看看III
管理员
- 积分
- 1308
|
- 如何判断一个多边形是凹多边形还是凸多边形?
- 1.角度和判断:将多边形每个顶点处的较小角(内角或外角)相加,如果小于(n-2)*180,则为凹多边形。(可以使用向量点乘来等价求两个向量的夹角,它的值(角)总是以较短的弧度来度量)
- 实现:
- public static bool IsConcavePolygon(Vector2[] points)
- {
- int totalAngle = (points.Length - 2) * 180;
- float angle = 0;
- for(int i=0;i<points.Length;i++)
- {
- Vector2 v1,v2;
- //向量1
- if(i==0)
- v1=points[points.Length-1]-points[i];
- else
- v1=points[i-1]-points[i];
- //向量2
- if(i==points.Length-1)
- v2=points[0]-points[i];
- else
- v2 = points[i+1]-points[i];
- //计算夹角:Mathf.Acos(Mathf.Clamp(Vector2.Dot(v1.normalized,to.normalized),-1f,1f))*57.29578f;
- float a = Vector2.Angle(v1,v2);
- angle+=a;
- }
- return angle<totalAngle;
- }
-
- 2.检测凹点:凸多变形的每个顶点的转向都应该是一致的,不一致的点就是凹点。(向量的叉乘)
- 实现:
- //假设传入的是逆时针单向链
- //判断两个向量的转向,如果是逆时针转,则为凸点,顺时针转则为凹点
- public static bool IsConcavePolygon(Vector2[] points)
- {
- for(int i=0;i<points.Length;i++)
- {
- Vector2 v1,v2;
- //向量1
- if(i==0)
- v1=points[points.Length-1]-points[i];
- else
- v1=points[i-1]-points[i];
- //向量2
- if(i==points.Length-1)
- v2=points[0]-points[i];
- else
- v2 = points[i+1]-points[i];
- //计算叉积,根据三维叉积公式计算,z轴为0
- float corss = v1.x*v2.y-v1.y*v2.x;
- if(corss>0)
- return true;
- }
- return false;
- }
-
复制代码 |
|