Route.cs 2.5 KB

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