/// <summary> /// Get a line segment intersect point. /// </summary> /// <param name="vector">Point.</param> /// <param name="point1">Line Point 1.</param> /// <param name="point2">Line Point 2.</param> /// <returns>Return value.</returns> public static Vector2 IntersectLineSegment(this Vector2 vector, Vector2 point1, Vector2 point2) { var dir = point1 - point2; dir.Normalize(); var point = (dir * Vector2.Dot(vector - point1, dir)) + point1; Bound2 bound; Bound2.FromPoints(ref point1, ref point2, out bound); if (!bound.Intersects(point)) { if ((vector - point1).magnitude <= (vector - point2).magnitude) { return(point1); } else { return(point2); } } return(point); }
/// <summary> /// Create bound around points. /// </summary> /// <param name="point1">Point1.</param> /// <param name="point2">Point2.</param> /// <param name="result">Bound result.</param> public static void FromPoints(ref Vector2 point1, ref Vector2 point2, out Bound2 result) { result.left = point1.x; result.right = point1.x; result.bottom = point1.y; result.top = point1.y; if (point2.x < result.left) { result.left = point2.x; } if (point2.x > result.right) { result.right = point2.x; } if (point2.y < result.bottom) { result.bottom = point2.y; } if (point2.y > result.top) { result.top = point2.y; } }
/// <summary> /// Create bound around points. /// </summary> /// <param name="point1">Point1.</param> /// <param name="point2">Point2.</param> /// <param name="result">Bound result.</param> public static void FromPoints(ref Vector2 point1, ref Vector2 point2, out Bound2 result) { result.left = point1.x; result.right = point1.x; result.bottom = point1.y; result.top = point1.y; if (point2.x < result.left) result.left = point2.x; if (point2.x > result.right) result.right = point2.x; if (point2.y < result.bottom) result.bottom = point2.y; if (point2.y > result.top) result.top = point2.y; }