TilemapPolygonObject.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using Microsoft.Xna.Framework;
  4. namespace MonoGame.Extended.Tilemaps
  5. {
  6. /// <summary>
  7. /// Represents a closed polygonal object in a tilemap.
  8. /// </summary>
  9. public class TilemapPolygonObject : TilemapObject
  10. {
  11. /// <summary>
  12. /// Gets or sets the vertices of the polygon relative to the object's position.
  13. /// </summary>
  14. public Vector2[] Points { get; set; }
  15. /// <summary>
  16. /// Gets the vertices of the polygon in world coordinates.
  17. /// </summary>
  18. public IEnumerable<Vector2> WorldPoints
  19. {
  20. get
  21. {
  22. foreach (var point in Points)
  23. {
  24. yield return Position + point;
  25. }
  26. }
  27. }
  28. /// <inheritdoc/>
  29. public override RectangleF Bounds
  30. {
  31. get
  32. {
  33. if (Points == null || Points.Length == 0)
  34. return new RectangleF(Position.X, Position.Y, 0, 0);
  35. // Calculate bounding box from all world points
  36. float minX = float.MaxValue;
  37. float minY = float.MaxValue;
  38. float maxX = float.MinValue;
  39. float maxY = float.MinValue;
  40. foreach (var worldPoint in WorldPoints)
  41. {
  42. minX = Math.Min(minX, worldPoint.X);
  43. minY = Math.Min(minY, worldPoint.Y);
  44. maxX = Math.Max(maxX, worldPoint.X);
  45. maxY = Math.Max(maxY, worldPoint.Y);
  46. }
  47. return new RectangleF(minX, minY, maxX - minX, maxY - minY);
  48. }
  49. }
  50. // NOTE: Will use BoundingPolygon2D
  51. /// <summary>
  52. /// Initializes a new instance of the <see cref="TilemapPolygonObject"/> class.
  53. /// </summary>
  54. /// <param name="id">The unique identifier for the object.</param>
  55. /// <param name="position">The position of the object (origin point).</param>
  56. /// <param name="points">The vertices of the polygon relative to the position.</param>
  57. public TilemapPolygonObject(int id, Vector2 position, Vector2[] points) : base(id, position)
  58. {
  59. Points = points;
  60. }
  61. }
  62. }