V2Tools.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using UnityEngine;
  2. using System.Collections;
  3. namespace RootMotion
  4. {
  5. /// <summary>
  6. /// Helper methods for dealing with 2-dimensional vectors.
  7. /// </summary>
  8. public static class V2Tools
  9. {
  10. /// <summary>
  11. /// Converts Vector3 to Vector2 on the XZ plane
  12. /// </summary>
  13. public static Vector2 XZ(Vector3 v)
  14. {
  15. return new Vector2(v.x, v.z);
  16. }
  17. /// <summary>
  18. /// Returns delta angle from 'dir1' to 'dir2' in degrees.
  19. /// </summary>
  20. public static float DeltaAngle(Vector2 dir1, Vector2 dir2)
  21. {
  22. float angle1 = Mathf.Atan2(dir1.x, dir1.y) * Mathf.Rad2Deg;
  23. float angle2 = Mathf.Atan2(dir2.x, dir2.y) * Mathf.Rad2Deg;
  24. return Mathf.DeltaAngle(angle1, angle2);
  25. }
  26. /// <summary>
  27. /// Returns delta angle from Vector3 'dir1' to Vector3 'dir2' on the XZ plane in degrees.
  28. /// </summary>
  29. public static float DeltaAngleXZ(Vector3 dir1, Vector3 dir2)
  30. {
  31. float angle1 = Mathf.Atan2(dir1.x, dir1.z) * Mathf.Rad2Deg;
  32. float angle2 = Mathf.Atan2(dir2.x, dir2.z) * Mathf.Rad2Deg;
  33. return Mathf.DeltaAngle(angle1, angle2);
  34. }
  35. /// <summary>
  36. /// Returns true if a line from 'p1' to 'p2' intersects a circle with position 'c' and radius 'r'.
  37. /// </summary>
  38. public static bool LineCircleIntersect(Vector2 p1, Vector2 p2, Vector2 c, float r)
  39. {
  40. Vector2 d = p2 - p1;
  41. Vector2 f = c - p1;
  42. float a = Vector2.Dot(d, d);
  43. float b = 2f * Vector2.Dot(f, d);
  44. float z = Vector2.Dot(f, f) - r * r;
  45. float discr = b * b - 4f * a * z;
  46. if (discr < 0f) return false;
  47. discr = Mathf.Sqrt(discr);
  48. float a2 = 2f * a;
  49. float t1 = (b - discr) / a2;
  50. float t2 = (b + discr) / a2;
  51. if (t1 >= 0f && t1 <= 1f) return true;
  52. if (t2 >= 0f && t2 <= 1f) return true;
  53. return false;
  54. }
  55. /// <summary>
  56. /// Returns true if an infinite ray 'dir' from position 'p1' intersects a circle with position 'c' and radius 'r'.
  57. /// </summary>
  58. public static bool RayCircleIntersect(Vector2 p1, Vector2 dir, Vector2 c, float r)
  59. {
  60. Vector2 p2 = p1 + dir;
  61. p1 -= c;
  62. p2 -= c;
  63. float dx = p2.x - p1.x;
  64. float dy = p2.y - p1.y;
  65. float dr = Mathf.Sqrt(Mathf.Pow(dx, 2f) + Mathf.Pow(dy, 2f));
  66. float D = p1.x * p2.y - p2.x * p1.y;
  67. float discr = Mathf.Pow(r, 2f) * Mathf.Pow(dr, 2f) - Mathf.Pow(D, 2f);
  68. return discr >= 0f;
  69. }
  70. }
  71. }