首页 > 代码库 > 2D空间中判断一点是否在三角形内
2D空间中判断一点是否在三角形内
本来打算做三角形填充多边形,但需要用到耳切法正在看。所以先研究了这个
要注意如果是XY坐标轴的2D空间,要取差乘分量z而不是y。
实现原理是,将三角形ABC三个边(AB,BC,CA)分别与比较点判断差乘,如果这3个差乘结果表示的方向一致,说明就在三角形内。
效果:
代码(Unity3D):
using UnityEngine; using System.Collections; using System.Collections.Generic; public class TriangleCollider : MonoBehaviour { public const float ERROR = 0.05f; public Transform trianglePoint1; public Transform trianglePoint2; public Transform trianglePoint3; public Transform comparePoint; public bool IsContract(Vector3 comparePoint) { var dir1 = trianglePoint2.position - trianglePoint1.position; var dir2 = trianglePoint3.position - trianglePoint2.position; var dir3 = trianglePoint1.position - trianglePoint3.position; var cross1 = Mathf.Sign(Vector3.Cross(dir1, comparePoint - trianglePoint1.position).y); var cross2 = Mathf.Sign(Vector3.Cross(dir2, comparePoint - trianglePoint2.position).y); var cross3 = Mathf.Sign(Vector3.Cross(dir3, comparePoint - trianglePoint3.position).y); var dir = cross1 == cross2 ? cross3 : cross1 == cross3 ? cross2 : cross1; cross1 = Mathf.Sign(Vector3.Cross(dir1, comparePoint - trianglePoint1.position).y + -dir * ERROR); cross2 = Mathf.Sign(Vector3.Cross(dir2, comparePoint - trianglePoint2.position).y + -dir * ERROR); cross3 = Mathf.Sign(Vector3.Cross(dir3, comparePoint - trianglePoint3.position).y + -dir * ERROR); return cross1 == cross2 && cross2 == cross3; } void OnDrawGizmos() { if (comparePoint == null) return; var oldColor = Gizmos.color; if (IsContract(comparePoint.position)) Gizmos.color = Color.red; Gizmos.DrawLine(trianglePoint1.position, trianglePoint2.position); Gizmos.DrawLine(trianglePoint2.position, trianglePoint3.position); Gizmos.DrawLine(trianglePoint3.position, trianglePoint1.position); Gizmos.color = oldColor; } }
为了加误差,所以多做了3次差乘。不过使用起来还算可以
2D空间中判断一点是否在三角形内
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。