using UnityEngine; public struct Line2D { public Vector2 start; public Vector2 end; public float slope { get { if (end.x == start.x) return 0; return (end.y - start.y) / (end.x - start.x); } } public float perpSlope { get { return -1 / slope; } } /// /// 计算给定点是否在线的左边 /// /// 给定点 /// 线 /// 是否在左边 public static bool PointAtLineLeft(Vector2 point, Line2D line) { return PointRelation(line, point) > 0; } /// /// 计算给定点是否在线的右边 /// /// 给定点 /// 线 /// 是否在右边 public static bool PointAtLineRight(Vector2 point, Line2D line) { return PointRelation(line, point) < 0; } /// /// 计算两个斜率是否垂直 /// /// 斜率1 /// 斜率2 /// 是否垂直 public static bool IsPerp(float slope1, float slope2) { return (slope1 * slope2 == -1); } /// /// 计算两条线的交点 /// /// 给定的线1 /// 给定的线2 /// 交点 public static Vector2 Line2DIntersect(Line2D line1, Line2D line2) { Vector2 _intersectPoint; _intersectPoint.x = (line1.slope * line1.start.x - line2.slope * line2.start.x + line2.start.y - line1.start.y) / (line1.slope - line2.slope); _intersectPoint.y = line1.slope * (_intersectPoint.x - line1.start.x) + line1.start.y; return _intersectPoint; } private static float PointRelation(Line2D line, Vector2 pt) { return (pt.y - line.start.y) * (line.end.x - line.start.x) - (pt.x - line.start.x) * (line.end.y - line.start.y); } public void DebugDraw(Color color) { Debug.DrawLine(new Vector3(start.x, 0, start.y), new Vector3(end.x, 0, end.y), color); } }