From 821ba0ec3b097e11da4164ab3f10be296e464506 Mon Sep 17 00:00:00 2001 From: Wojciech Figat Date: Tue, 14 Dec 2021 17:00:13 +0100 Subject: [PATCH] Add `Rectangle.Distance` for distance between rectangle and a point --- Source/Engine/Core/Math/Rectangle.cs | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/Source/Engine/Core/Math/Rectangle.cs b/Source/Engine/Core/Math/Rectangle.cs index bb085ef6a..15810d66e 100644 --- a/Source/Engine/Core/Math/Rectangle.cs +++ b/Source/Engine/Core/Math/Rectangle.cs @@ -284,16 +284,30 @@ namespace FlaxEngine Vector2 toExpand = Size * (scale - 1.0f) * 0.5f; return new Rectangle(Location - toExpand * 0.5f, Size + toExpand); } - + /// /// Computed nearest distance between 2 rectangles. /// - /// Firat rectangle + /// First rectangle /// Second rectangle /// Resulting distance, 0 if overlapping 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; + } + + /// + /// Computed distance between rectangle and the point. + /// + /// The rectangle. + /// The point. + /// The resulting distance, 0 if point is inside the rectangle. + 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); } ///