Advertisement
fuccpuff

Untitled

Nov 12th, 2023
11
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.89 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5.  
  6. public class Boat : MonoBehaviour
  7. {
  8. [SerializeField] private float speed = 3f;
  9. public Queue<GraphObject> _currentWay = new Queue<GraphObject>();
  10. [HideInInspector] public List<GraphObject> VisitedPoints = new List<GraphObject>();
  11. public List<WayInfo> AllShortestWays => GraphMatrix.AllShortestWays;
  12.  
  13. // Метод для планирования и инициализации маршрута
  14. public void SetWayAndGo(string path)
  15. {
  16. _currentWay = new Queue<GraphObject>();
  17.  
  18. for (int i = 0; i < path.Length; i++)
  19. {
  20. GraphObject node = GraphObject.AllGraphObjects.FirstOrDefault(o => o.Letter == path[i]);
  21. if (node == null)
  22. {
  23. Debug.LogError($"No GraphObject found for letter: {path[i]}");
  24. return; // Выход, если узел не найден
  25. }
  26.  
  27. if (i == 0)
  28. {
  29. transform.position = node.transform.position;
  30. }
  31.  
  32. if (i < path.Length - 1)
  33. {
  34. var nextNode = GraphObject.AllGraphObjects.FirstOrDefault(o => o.Letter == path[i + 1]);
  35. var way = AllShortestWays.FirstOrDefault(info => info.A == node && info.B == nextNode);
  36. if (!way.Equals(default(WayInfo))) // Проверяем, что way не является значением по умолчанию
  37. {
  38. for (int j = 1; j < way.Way.Count; j++) // Пропускаем первую точку в каждом пути
  39. {
  40. _currentWay.Enqueue(way.Way[j]);
  41. }
  42. }
  43. }
  44. else
  45. {
  46. _currentWay.Enqueue(node);
  47. }
  48. }
  49.  
  50. StartCoroutine(Go()); // Запускаем корутину для движения лодки
  51. }
  52.  
  53. // Метод вызывается при посещении точки
  54. public void OnPointWent(GraphObject point)
  55. {
  56. if (_currentWay.Count > 0 && _currentWay.Peek() == point)
  57. {
  58. VisitedPoints.Add(_currentWay.Dequeue());
  59. }
  60. }
  61.  
  62. // Корутина для движения лодки
  63. private IEnumerator Go()
  64. {
  65. while (_currentWay.Count > 0)
  66. {
  67. var currentNode = _currentWay.Peek();
  68. transform.position = Vector3.MoveTowards(transform.position, currentNode.transform.position, speed * Time.deltaTime);
  69.  
  70. if (Vector3.Distance(transform.position, currentNode.transform.position) < 0.1f)
  71. {
  72. OnPointWent(currentNode);
  73. }
  74.  
  75. yield return null;
  76. }
  77.  
  78. Debug.Log("Route completed"); // Маршрут завершен
  79. }
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement