1
#region File Description
2 //-----------------------------------------------------------------------------
3 // RectangleExtensions.cs
5 // Microsoft XNA Community Game Platform
6 // Copyright (C) Microsoft Corporation. All rights reserved.
7 //-----------------------------------------------------------------------------
11 using Microsoft
.Xna
.Framework
;
13 namespace Platformer2D
16 /// A set of helpful methods for working with rectangles.
18 public static class RectangleExtensions
21 /// Calculates the signed depth of intersection between two rectangles.
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.
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
;
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
)
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
);
59 /// Gets the position of the center of the bottom edge of the rectangle.
61 public static Vector2
GetBottomCenter(this Rectangle rect
)
63 return new Vector2(rect
.X
+ rect
.Width
/ 2.0f
, rect
.Bottom
);