Route.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using System;
  2. using System.Collections.Generic;
  3. using Roads;
  4. using UnityEditor;
  5. using UnityEngine;
  6. using UnityEngine.Rendering;
  7. namespace Routes
  8. {
  9. [Serializable]
  10. public struct RouteItem
  11. {
  12. public Turn turn;
  13. public RoadDirection from;
  14. public RoadDirection to;
  15. public void Apply()
  16. {
  17. if (turn.comingFrom != from || turn.goingTo != to)
  18. {
  19. turn.comingFrom = from;
  20. turn.goingTo = to;
  21. turn.UpdateArrows();
  22. }
  23. }
  24. public void Clear()
  25. {
  26. if (turn.comingFrom != RoadDirection.None || turn.goingTo != RoadDirection.None)
  27. {
  28. turn.comingFrom = RoadDirection.None;
  29. turn.goingTo = RoadDirection.None;
  30. turn.UpdateArrows();
  31. }
  32. }
  33. }
  34. public class Route : MonoBehaviour
  35. {
  36. public List<RouteItem> items;
  37. public StraightRoadExtras start;
  38. public StraightRoadExtras finish;
  39. private int visibleLength;
  40. private int visibleStart;
  41. private int VisibleStart => Math.Max(0, visibleStart - 1);
  42. private int VisibleEnd => Math.Min(items.Count, VisibleStart + visibleLength);
  43. public delegate void OnStartEnteredEvent();
  44. public event OnStartEnteredEvent OnStartEntered;
  45. public delegate void OnFinishPassedEvent();
  46. public event OnFinishPassedEvent OnFinishPassed;
  47. private void Start()
  48. {
  49. start.ShowArc();
  50. SetupEvents();
  51. var routeManager = GetComponentInParent<RouteManager>();
  52. visibleStart = 0;
  53. visibleLength = routeManager.visibleLength;
  54. items.ForEach((item) => item.turn.OnTriggerExitBicycle = NextTurn);
  55. UpdateRouteItems();
  56. }
  57. private void SetupEvents()
  58. {
  59. start.OnArcEntered += () =>
  60. {
  61. OnStartEntered?.Invoke();
  62. };
  63. finish.OnArcPassed += () =>
  64. {
  65. OnFinishPassed?.Invoke();
  66. };
  67. }
  68. private void NextTurn()
  69. {
  70. Debug.Log("Route: left intersection - show next turn");
  71. visibleStart++;
  72. UpdateRouteItems();
  73. }
  74. private void UpdateRouteItems()
  75. {
  76. if (VisibleEnd == items.Count - 1)
  77. {
  78. finish.ShowArc();
  79. }
  80. for (var i = 0; i < VisibleEnd; i++)
  81. {
  82. var item = items[i];
  83. if (i >= VisibleStart)
  84. {
  85. item.Apply();
  86. }
  87. else
  88. {
  89. item.Clear();
  90. }
  91. }
  92. }
  93. }
  94. }