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;
|
}
|
}
|
|
/// <summary>
|
/// 计算给定点是否在线的左边
|
/// </summary>
|
/// <param name="point">给定点</param>
|
/// <param name="line">线</param>
|
/// <returns>是否在左边</returns>
|
public static bool PointAtLineLeft(Vector2 point, Line2D line)
|
{
|
return PointRelation(line, point) > 0;
|
}
|
|
/// <summary>
|
/// 计算给定点是否在线的右边
|
/// </summary>
|
/// <param name="point">给定点</param>
|
/// <param name="line">线</param>
|
/// <returns>是否在右边</returns>
|
public static bool PointAtLineRight(Vector2 point, Line2D line)
|
{
|
return PointRelation(line, point) < 0;
|
}
|
|
/// <summary>
|
/// 计算两个斜率是否垂直
|
/// </summary>
|
/// <param name="slope1">斜率1</param>
|
/// <param name="slope2">斜率2</param>
|
/// <returns>是否垂直</returns>
|
public static bool IsPerp(float slope1, float slope2)
|
{
|
return (slope1 * slope2 == -1);
|
}
|
|
/// <summary>
|
/// 计算两条线的交点
|
/// </summary>
|
/// <param name="line1">给定的线1</param>
|
/// <param name="line2">给定的线2</param>
|
/// <returns>交点</returns>
|
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);
|
}
|
}
|