diff --git a/MLEM/Extensions/NumberExtensions.cs b/MLEM/Extensions/NumberExtensions.cs index 3fd4db6..ecb4a3b 100644 --- a/MLEM/Extensions/NumberExtensions.cs +++ b/MLEM/Extensions/NumberExtensions.cs @@ -200,5 +200,24 @@ namespace MLEM.Extensions { 0, 0, 0, 1)); } + /// + /// Returns the amount that the rectangle is penetrating the rectangle by. + /// If a penetration on both axes is occuring, the one with the lower value is returned. + /// This is useful for collision detection, as it can be used to push colliding objects out of each other. + /// + /// The rectangle to do the penetration + /// The rectangle that should be penetrated + /// A penetration vector, or if the rectangles don't intersect + public static Vector2 Penetrate(this RectangleF rect, RectangleF other) { + var intersection = RectangleF.Intersect(rect, other); + if (intersection.IsEmpty) + return Vector2.Zero; + if (intersection.Width < intersection.Height) { + return new Vector2(rect.Center.X < other.Center.X ? intersection.Width : -intersection.Width, 0); + } else { + return new Vector2(0, rect.Center.Y < other.Center.Y ? intersection.Height : -intersection.Height); + } + } + } } \ No newline at end of file