Circle2D.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #if UNITY_EDITOR
  2. using UnityEngine;
  3. namespace O3DWB
  4. {
  5. public struct Circle2D
  6. {
  7. #region Private Variables
  8. private Vector2 _center;
  9. private float _radius;
  10. #endregion
  11. #region Public Properties
  12. public Vector2 Center { get { return _center; } set { _center = value; } }
  13. public float Radius { get { return _radius; } set { _radius = value; } }
  14. #endregion
  15. #region Constructors
  16. public Circle2D(Vector2 center, float radius)
  17. {
  18. _center = center;
  19. _radius = radius;
  20. }
  21. #endregion
  22. #region Public Methods
  23. /// <summary>
  24. /// This method can be used to check if the specified 2D ray intersects the circle.
  25. /// </summary>
  26. /// <param name="ray">
  27. /// The ray involved in the intersection test.
  28. /// </param>
  29. /// <param name="t">
  30. /// If the ray intersects the circle, this will hold the intersection offset between
  31. /// the ray and the circle. It will always have a value in the interval [0, 1]. If no
  32. /// intersection happens, it will be set to 0.
  33. /// </param>
  34. /// <returns>
  35. /// True if an intersection happens and false otherwise.
  36. /// </returns>
  37. public bool Raycast(Ray2D ray, out float t)
  38. {
  39. t = 0.0f;
  40. // Calculate the equation coefficients
  41. Vector2 fromCenterToRayOrigin = ray.Origin - _center;
  42. float a = Vector3.Dot(ray.Direction, ray.Direction);
  43. float b = 2.0f * Vector3.Dot(fromCenterToRayOrigin, ray.Direction);
  44. float c = Vector3.Dot(fromCenterToRayOrigin, fromCenterToRayOrigin) - _radius * _radius;
  45. // If the equation can be solved, it means that ray intersects the circle
  46. float t1, t2;
  47. if (Equation.SolveQuadratic(a, b, c, out t1, out t2))
  48. {
  49. // Make sure that the ray does not intersect the circle from behind or that the intersection
  50. // offset doesn't exceed the length of the ray direction.
  51. if (t1 < 0.0f || t1 > 1.0f) return false;
  52. // Store the intersection offset and return true
  53. t = t1;
  54. return true;
  55. }
  56. else return false; // The equation could not be solved, so no intersection occurs
  57. }
  58. /// <summary>
  59. /// Ths method can be used to check if the specified ray intersects the
  60. /// circle. It returns true if there is an intersection and false otherwise.
  61. /// </summary>
  62. public bool Raycast(Ray2D ray)
  63. {
  64. float t;
  65. return Raycast(ray, out t);
  66. }
  67. public bool ContainsPoint(Vector2 point)
  68. {
  69. return (point - Center).magnitude <= Radius;
  70. }
  71. #endregion
  72. }
  73. }
  74. #endif