Path.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace Assets.Plugins.SmartLevelsMap.Scripts
  4. {
  5. public class Path : MonoBehaviour
  6. {
  7. [HideInInspector]
  8. public List<Transform> Waypoints = new List<Transform>();
  9. [HideInInspector]
  10. public bool IsCurved;
  11. [HideInInspector]
  12. public Color GizmosColor = Color.white;
  13. [HideInInspector]
  14. public float GizmosRadius = 10.0f;
  15. public void OnDrawGizmos()
  16. {
  17. Gizmos.color = GizmosColor;
  18. for (int i = 0; i < Waypoints.Count; i++)
  19. {
  20. Gizmos.DrawSphere(Waypoints[i].transform.position, GizmosRadius);
  21. if (i < Waypoints.Count - 1)
  22. DrawPart(i);
  23. }
  24. }
  25. private void DrawPart(int ind)
  26. {
  27. if (IsCurved)
  28. {
  29. Vector2[] devidedPoints = GetDivededPoints(ind);
  30. for (int i = 0; i < devidedPoints.Length - 1; i++)
  31. Gizmos.DrawLine(devidedPoints[i], devidedPoints[i + 1]);
  32. }
  33. else
  34. {
  35. Gizmos.DrawLine(Waypoints[ind].position, Waypoints[(ind + 1) % Waypoints.Count].position);
  36. }
  37. }
  38. private Vector2[] GetDivededPoints(int ind)
  39. {
  40. Vector2[] points = new Vector2[11];
  41. int pointInd = 0;
  42. int[] indexes = GetSplinePointIndexes(ind, true);
  43. Vector2 a = Waypoints[indexes[0]].transform.position;
  44. Vector2 b = Waypoints[indexes[1]].transform.position;
  45. Vector2 c = Waypoints[indexes[2]].transform.position;
  46. Vector2 d = Waypoints[indexes[3]].transform.position;
  47. for (float t = 0; t <= 1.001f; t += 0.1f)
  48. points[pointInd++] = SplineCurve.GetPoint(a, b, c, d, t);
  49. return points;
  50. }
  51. public int[] GetSplinePointIndexes(int baseInd, bool isForwardDirection)
  52. {
  53. int dInd = isForwardDirection ? 1 : -1;
  54. return new int[]
  55. {
  56. Mathf.Clamp(baseInd - dInd, 0, Waypoints.Count - 1),
  57. baseInd,
  58. Mathf.Clamp(baseInd + dInd, 0, Waypoints.Count - 1),
  59. Mathf.Clamp(baseInd + 2*dInd, 0, Waypoints.Count - 1)
  60. };
  61. }
  62. public float GetLength()
  63. {
  64. float length = 0;
  65. for (int i = 0; i < Waypoints.Count; i++)
  66. {
  67. Vector2 p1 = Waypoints[i].transform.position;
  68. Vector2 p2 = Waypoints[(i + 1) % Waypoints.Count].transform.position;
  69. length += Vector2.Distance(p1, p2);
  70. }
  71. return length;
  72. }
  73. public float GetLength(int startInd)
  74. {
  75. return Vector2.Distance(
  76. Waypoints[startInd].transform.position,
  77. Waypoints[(startInd + 1) % Waypoints.Count].transform.position);
  78. }
  79. }
  80. }