EllipseF.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using System.Runtime.Serialization;
  3. using Microsoft.Xna.Framework;
  4. namespace MonoGame.Extended
  5. {
  6. [DataContract]
  7. public struct EllipseF : IEquatable<EllipseF>, IEquatableByRef<EllipseF>, IShapeF
  8. {
  9. [DataMember] public Vector2 Center { get; set; }
  10. [DataMember] public float RadiusX { get; set; }
  11. [DataMember] public float RadiusY { get; set; }
  12. public Vector2 Position
  13. {
  14. get => Center;
  15. set => Center = value;
  16. }
  17. public EllipseF(Vector2 center, float radiusX, float radiusY)
  18. {
  19. Center = center;
  20. RadiusX = radiusX;
  21. RadiusY = radiusY;
  22. }
  23. public float Left => Center.X - RadiusX;
  24. public float Top => Center.Y - RadiusY;
  25. public float Right => Center.X + RadiusX;
  26. public float Bottom => Center.Y + RadiusY;
  27. public RectangleF BoundingRectangle
  28. {
  29. get
  30. {
  31. var minX = Left;
  32. var minY = Top;
  33. var maxX = Right;
  34. var maxY = Bottom;
  35. return new RectangleF(minX, minY, maxX - minX, maxY - minY);
  36. }
  37. }
  38. public bool Contains(float x, float y)
  39. {
  40. float xCalc = (float) (Math.Pow(x - Center.X, 2) / Math.Pow(RadiusX, 2));
  41. float yCalc = (float) (Math.Pow(y - Center.Y, 2) / Math.Pow(RadiusY, 2));
  42. return xCalc + yCalc <= 1;
  43. }
  44. public bool Contains(Vector2 point)
  45. {
  46. return Contains(point.X, point.Y);
  47. }
  48. public bool Equals(EllipseF ellispse)
  49. {
  50. return Equals(ref ellispse);
  51. }
  52. public bool Equals(ref EllipseF ellispse)
  53. {
  54. // ReSharper disable once CompareOfFloatsByEqualityOperator
  55. return ellispse.Center == Center
  56. && ellispse.RadiusX == RadiusX
  57. && ellispse.RadiusY == RadiusY;
  58. }
  59. public override bool Equals(object obj)
  60. {
  61. return obj is EllipseF && Equals((EllipseF)obj);
  62. }
  63. public override int GetHashCode()
  64. {
  65. unchecked
  66. {
  67. var hashCode = Center.GetHashCode();
  68. hashCode = (hashCode * 397) ^ RadiusX.GetHashCode();
  69. hashCode = (hashCode * 397) ^ RadiusY.GetHashCode();
  70. return hashCode;
  71. }
  72. }
  73. public override string ToString()
  74. {
  75. return $"Centre: {Center}, RadiusX: {RadiusX}, RadiusY: {RadiusY}";
  76. }
  77. public static bool operator ==(EllipseF first, EllipseF second)
  78. {
  79. return first.Equals(ref second);
  80. }
  81. public static bool operator !=(EllipseF first, EllipseF second)
  82. {
  83. return !(first == second);
  84. }
  85. }
  86. }