Add Rectangle.Distance for distance between rectangle and a point

This commit is contained in:
2021-12-14 17:00:13 +01:00
parent fc2a7d98fa
commit 821ba0ec3b
+17 -3
View File
@@ -284,16 +284,30 @@ namespace FlaxEngine
Vector2 toExpand = Size * (scale - 1.0f) * 0.5f;
return new Rectangle(Location - toExpand * 0.5f, Size + toExpand);
}
/// <summary>
/// Computed nearest distance between 2 rectangles.
/// </summary>
/// <param name="a">Firat rectangle</param>
/// <param name="a">First rectangle</param>
/// <param name="b">Second rectangle</param>
/// <returns>Resulting distance, 0 if overlapping</returns>
public static float Distance(Rectangle a, Rectangle b)
{
return Vector2.Max(Vector2.Zero, Vector2.Abs(a.Center - b.Center) - ((a.Size + b.Size) * 0.5f)).Length;
return Vector2.Max(Vector2.Zero, Vector2.Abs(a.Center - b.Center) - ((a.Size + b.Size) * 0.5f)).Length;
}
/// <summary>
/// Computed distance between rectangle and the point.
/// </summary>
/// <param name="rect">The rectangle.</param>
/// <param name="p">The point.</param>
/// <returns>The resulting distance, 0 if point is inside the rectangle.</returns>
public static float Distance(Rectangle rect, Vector2 p)
{
var max = rect.Location + rect.Size;
var dx = Mathf.Max(Mathf.Max(rect.Location.X - p.X, p.X - max.X), 0);
var dy = Mathf.Max(Math.Max(rect.Location.Y - p.Y, p.Y - max.Y), 0);
return Mathf.Sqrt(dx * dx + dy * dy);
}
/// <summary>