RectangleExtensions.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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
  9. using System;
  10. using Microsoft.Xna.Framework;
  11. namespace Platformer
  12. {
  13. /// <summary>
  14. /// A set of helpful methods for working with rectangles.
  15. /// </summary>
  16. public static class RectangleExtensions
  17. {
  18. /// <summary>
  19. /// Calculates the signed depth of intersection between two rectangles.
  20. /// </summary>
  21. /// <returns>
  22. /// The amount of overlap between two intersecting rectangles. These
  23. /// depth values can be negative depending on which wides the rectangles
  24. /// intersect. This allows callers to determine the correct direction
  25. /// to push objects in order to resolve collisions.
  26. /// If the rectangles are not intersecting, Vector2.Zero is returned.
  27. /// </returns>
  28. public static Vector2 GetIntersectionDepth(this Rectangle rectA, Rectangle rectB)
  29. {
  30. // Calculate half sizes.
  31. float halfWidthA = rectA.Width / 2.0f;
  32. float halfHeightA = rectA.Height / 2.0f;
  33. float halfWidthB = rectB.Width / 2.0f;
  34. float halfHeightB = rectB.Height / 2.0f;
  35. // Calculate centers.
  36. Vector2 centerA = new Vector2(rectA.Left + halfWidthA, rectA.Top + halfHeightA);
  37. Vector2 centerB = new Vector2(rectB.Left + halfWidthB, rectB.Top + halfHeightB);
  38. // Calculate current and minimum-non-intersecting distances between centers.
  39. float distanceX = centerA.X - centerB.X;
  40. float distanceY = centerA.Y - centerB.Y;
  41. float minDistanceX = halfWidthA + halfWidthB;
  42. float minDistanceY = halfHeightA + halfHeightB;
  43. // If we are not intersecting at all, return (0, 0).
  44. if (Math.Abs(distanceX) >= minDistanceX || Math.Abs(distanceY) >= minDistanceY)
  45. return Vector2.Zero;
  46. // Calculate and return intersection depths.
  47. float depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
  48. float depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
  49. return new Vector2(depthX, depthY);
  50. }
  51. /// <summary>
  52. /// Gets the position of the center of the bottom edge of the rectangle.
  53. /// </summary>
  54. public static Vector2 GetBottomCenter(this Rectangle rect)
  55. {
  56. return new Vector2(rect.X + rect.Width / 2.0f, rect.Bottom);
  57. }
  58. }
  59. }