tasting on MonoGame
[tastes.git] / Platformer2D / Platformer2D.Core / Game / RectangleExtensions.cs
blob1a7ceef4ac4410e75cf0924251e48772b456071a
1 #region File Description
2 //-----------------------------------------------------------------------------
3 // RectangleExtensions.cs
4 //
5 // Microsoft XNA Community Game Platform
6 // Copyright (C) Microsoft Corporation. All rights reserved.
7 //-----------------------------------------------------------------------------
8 #endregion
10 using System;
11 using Microsoft.Xna.Framework;
13 namespace Platformer2D
15 /// <summary>
16 /// A set of helpful methods for working with rectangles.
17 /// </summary>
18 public static class RectangleExtensions
20 /// <summary>
21 /// Calculates the signed depth of intersection between two rectangles.
22 /// </summary>
23 /// <returns>
24 /// The amount of overlap between two intersecting rectangles. These
25 /// depth values can be negative depending on which wides the rectangles
26 /// intersect. This allows callers to determine the correct direction
27 /// to push objects in order to resolve collisions.
28 /// If the rectangles are not intersecting, Vector2.Zero is returned.
29 /// </returns>
30 public static Vector2 GetIntersectionDepth(this Rectangle rectA, Rectangle rectB)
32 // Calculate half sizes.
33 float halfWidthA = rectA.Width / 2.0f;
34 float halfHeightA = rectA.Height / 2.0f;
35 float halfWidthB = rectB.Width / 2.0f;
36 float halfHeightB = rectB.Height / 2.0f;
38 // Calculate centers.
39 Vector2 centerA = new Vector2(rectA.Left + halfWidthA, rectA.Top + halfHeightA);
40 Vector2 centerB = new Vector2(rectB.Left + halfWidthB, rectB.Top + halfHeightB);
42 // Calculate current and minimum-non-intersecting distances between centers.
43 float distanceX = centerA.X - centerB.X;
44 float distanceY = centerA.Y - centerB.Y;
45 float minDistanceX = halfWidthA + halfWidthB;
46 float minDistanceY = halfHeightA + halfHeightB;
48 // If we are not intersecting at all, return (0, 0).
49 if (Math.Abs(distanceX) >= minDistanceX || Math.Abs(distanceY) >= minDistanceY)
50 return Vector2.Zero;
52 // Calculate and return intersection depths.
53 float depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
54 float depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
55 return new Vector2(depthX, depthY);
58 /// <summary>
59 /// Gets the position of the center of the bottom edge of the rectangle.
60 /// </summary>
61 public static Vector2 GetBottomCenter(this Rectangle rect)
63 return new Vector2(rect.X + rect.Width / 2.0f, rect.Bottom);