MathUtils.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using UnityEngine;
  2. namespace ARLocation
  3. {
  4. public static class MathUtils
  5. {
  6. public enum LineSegmentRegion
  7. {
  8. Start,
  9. Middle,
  10. End,
  11. }
  12. public class PointLineSegmentDistanceResult
  13. {
  14. public float Distance;
  15. public LineSegmentRegion Region;
  16. }
  17. public static PointLineSegmentDistanceResult PointLineSegmentDistance(Vector2 point, Vector2 a, Vector2 b)
  18. {
  19. var result = new PointLineSegmentDistanceResult { };
  20. var ap = point - a;
  21. var ab = b - a;
  22. var bp = point - b;
  23. float proj = Vector3.Dot(ap, ab) / ab.magnitude;
  24. float u = proj / ab.magnitude;
  25. if (u < 0)
  26. {
  27. result.Distance = ap.magnitude;
  28. result.Region = LineSegmentRegion.Start;
  29. }
  30. else if (u > 1)
  31. {
  32. result.Distance = bp.magnitude;
  33. result.Region = LineSegmentRegion.End;
  34. }
  35. else
  36. {
  37. result.Distance = Mathf.Sqrt(ap.sqrMagnitude - proj * proj);
  38. result.Region = LineSegmentRegion.Middle;
  39. }
  40. return result;
  41. }
  42. public static Vector2 HorizontalVector(Vector3 v)
  43. {
  44. return new Vector2(v.x, v.z);
  45. }
  46. public static Vector3 HorizontalVectorToVector3(Vector2 v, float y = 0.0f)
  47. {
  48. return new Vector3(v.x, y, v.y);
  49. }
  50. public static float HorizontalDistance(Vector3 a, Vector3 b)
  51. {
  52. return Vector2.Distance(HorizontalVector(a), HorizontalVector(b));
  53. }
  54. public static Vector3 SetY(Vector3 v, float y)
  55. {
  56. return new Vector3(v.x, y, v.z);
  57. }
  58. public static Vector3 SetXZ(Vector3 v, Vector3 w)
  59. {
  60. return new Vector3(w.x, v.y, w.z);
  61. }
  62. public static float DegreesToRadians(float degrees)
  63. {
  64. return Mathf.PI * degrees / 180.0f;
  65. }
  66. public static float RadiansToDegrees(float degrees)
  67. {
  68. return 180.0f * degrees / Mathf.PI;
  69. }
  70. public static class Double
  71. {
  72. public static double DegreesToRadians(double degrees)
  73. {
  74. return System.Math.PI * degrees / 180.0;
  75. }
  76. public static double RadiansToDegrees(double degrees)
  77. {
  78. return 180.0 * degrees / System.Math.PI;
  79. }
  80. }
  81. }
  82. }