protected static Vector2 GetIntersectionRectangle(CollisionUnit A, CollisionUnit B)
{
// Calculate half sizes.
float halfWidthA = (A.GetLowerRight().X - A.GetUpperLeft().X) / 2.0f;
float halfHeightA = (A.GetLowerRight().Y - A.GetUpperLeft().Y) / 2.0f;
float halfWidthB = (B.GetLowerRight().X - B.GetUpperLeft().X) / 2.0f;
float halfHeightB = (B.GetLowerRight().Y - B.GetUpperLeft().Y) / 2.0f;
// Calculate centers.
Vector2 centerA = new Vector2(A.GetUpperLeft().X + halfWidthA, A.GetUpperLeft().Y + halfHeightA);
Vector2 centerB = new Vector2(B.GetUpperLeft().X + halfWidthB, B.GetUpperLeft().Y + 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)
return Vector2.Zero;
// Calculate and return intersection depths.
float depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
float depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
return new Vector2(depthX, depthY);
}