Microsoft.Xna.Framework.RectangleExtension.GetIntersectionDepth C# (CSharp) Method

GetIntersectionDepth() public static method

Calculates the signed depth of intersection between two rectangles.
public static GetIntersectionDepth ( this rectA, Rectangle rectB, Vector2 &depth ) : bool
rectA this
rectB Rectangle
depth Vector2
return bool
        public static bool GetIntersectionDepth(this Rectangle rectA, Rectangle rectB, out Vector2 depth)
        {
            // Calculate half sizes.
            float halfWidthA = rectA.Width / 2.0f;
            float halfHeightA = rectA.Height / 2.0f;
            float halfWidthB = rectB.Width / 2.0f;
            float halfHeightB = rectB.Height / 2.0f;

            // Calculate centers.
            Vector2 centerA = new Vector2(rectA.Left + halfWidthA, rectA.Top + halfHeightA);
            Vector2 centerB = new Vector2(rectB.Left + halfWidthB, rectB.Top + halfHeightB);

            // Calculate current and minimum-non-intersecting distances between centers.
            float distanceX = centerA.X - centerB.X;
            float distanceY = centerA.Y - centerB.Y;
            float minDistanceX = halfWidthA + halfWidthB;
            float minDistanceY = halfHeightA + halfHeightB;

            // If we are not intersecting at all, return (0, 0).
            if (Math.Abs(distanceX) > minDistanceX || Math.Abs(distanceY) > minDistanceY)
            {
                depth = Vector2.Zero;
                return false;
            }

            // Calculate and return intersection depths.
            float depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
            float depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;

            depth = new Vector2(depthX, depthY);
            return true;
        }