using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; using System; using UnityEngine.UIElements; public class PathUtils { NavMeshPath _path; bool _isPathCalculated = false; Vector3 _calculatedFromPos; Vector3 _calculatedToPos; bool _isSuccessesCalculatedPath = false; bool _isNeedCalculatePath; float _totalDistance = 0; // totalDistance == float.MaxValue - путь до объекта не построен успешно успешно // isPathAlreadyCalculated - если путь до этого уже простроен public Vector3 GetPointAtPercentage(Vector3 fromPos, Vector3 toPos, float percentage,out float totalDistance, out bool isPathAlreadyCalculated) { _isNeedCalculatePath = false; if (_isPathCalculated) { if (_calculatedFromPos != fromPos || _calculatedToPos != toPos) { _isNeedCalculatePath = true; isPathAlreadyCalculated = false; } else { isPathAlreadyCalculated = true; _isNeedCalculatePath = false; } } else { _isNeedCalculatePath = true; isPathAlreadyCalculated = false; } if (_isNeedCalculatePath) { _isPathCalculated = false; _path = new NavMeshPath(); _isSuccessesCalculatedPath = NavMesh.CalculatePath(fromPos, toPos, NavMesh.AllAreas, _path); _calculatedFromPos = fromPos; _calculatedToPos = toPos; _isPathCalculated = true; } if (_isSuccessesCalculatedPath) { if (_isNeedCalculatePath) { _totalDistance = 0f; for (int i = 1; i < _path.corners.Length; i++) { _totalDistance += Vector3.Distance(_path.corners[i - 1], _path.corners[i]); } } totalDistance = _totalDistance; float targetDistance = _totalDistance * percentage; float accumulatedDistance = 0f; for (int i = 1; i < _path.corners.Length; i++) { float segmentDistance = Vector3.Distance(_path.corners[i - 1], _path.corners[i]); if (accumulatedDistance + segmentDistance >= targetDistance) { // Находим точку на текущем сегменте float remainingDistance = targetDistance - accumulatedDistance; Vector3 direction = (_path.corners[i] - _path.corners[i - 1]).normalized; return _path.corners[i - 1] + direction * remainingDistance; } accumulatedDistance += segmentDistance; } } else { totalDistance = float.MaxValue; } return fromPos; } } public class TeleportationChecker { public NavMeshAgent _agent; public float BaseSpeed = 3.0f; public float Speed { get => BaseSpeed * KSpeed; } public float ElapsedTimeMax = 70.0f; public float KSpeed = 1f; // Коэффициент скорости public enum TypeMove { Warp, Move, Nothing } PathUtils _pathUtils; public TeleportationChecker(NavMeshAgent agent) { _agent = agent; _pathUtils = new PathUtils(); } float textScale = 10f; public TypeMove IsNeedWarp(Vector3 oldPos, DateTime oldTime, Vector3 newPos, DateTime newTime, float diffSecondsLastTick, DateTime currentTime, out Vector3 warpPosition) { ; float elapsedTimeSeconds = (float)(newTime - oldTime).TotalSeconds; float currentTimeSeconds = (float)(currentTime - oldTime).TotalSeconds; float maxDistance = Speed * diffSecondsLastTick; Vector3 targetPoint = _pathUtils.GetPointAtPercentage(oldPos, newPos, currentTimeSeconds / elapsedTimeSeconds, out float actualDistance, out bool isPathAlreadyCalculated); // Если не можем дойти то возвращаем старую позицию if (actualDistance == float.MaxValue) { warpPosition = oldPos; return TypeMove.Warp; } // Обрабатываем только те задержка которых была меньше 10 секунд до следующей точки if (elapsedTimeSeconds > ElapsedTimeMax) { warpPosition = oldPos; return TypeMove.Warp; } if (isPathAlreadyCalculated) { float speed = actualDistance / elapsedTimeSeconds; if (speed < 0.8 * Speed) { // Другая логика обработки maxDistance = float.MinValue; // Перерасчитываем время с которого начнём перемещения // высчитываем время необходимое для прохода с помщью 0.9 от максимальной float localTotalTime = actualDistance / ((float) 0.9 * Speed); float localTimeBegin = (elapsedTimeSeconds - (float)localTotalTime); if (currentTimeSeconds > localTimeBegin) { targetPoint = _pathUtils.GetPointAtPercentage(oldPos, newPos, (currentTimeSeconds - localTimeBegin )/ localTotalTime, out actualDistance, out isPathAlreadyCalculated); warpPosition = targetPoint; return TypeMove.Move; } } } float currentDistance = Vector3.Distance(_agent.transform.position, targetPoint); //Debug.Log($"{currentDistance} {maxDistance}"); if (currentDistance - textScale * _agent.radius < maxDistance ) { Debug.Log("Move"); warpPosition = targetPoint; return TypeMove.Move; } else { warpPosition = oldPos; if (isPathAlreadyCalculated) { // Уже было совершено перемещение по точкам return TypeMove.Nothing; } else { // позиция новая перемещаем return TypeMove.Warp; } } } } public class PersonScript : MonoBehaviour { [Header("Данные сотрудника")] public string FIO; //ФИО сотрудника public string Tabnomer; //Серийный номер сотрудника [Header("Компоненты сотрудника")] [SerializeField] private Animator PersonAnimator; //Аниматор [SerializeField] private NavMeshAgent NavMeshAgent; //ИИ [SerializeField] private int CurrentPoint; //Текущая точка [SerializeField] private ThanksStASSForTheNiceMethod Delogger; //Скрипт с данными [SerializeField] private Uiika Uiika; [SerializeField] private Canvas NoSignalCanvas; public VisualTreeAsset MainUIPrefab; //private Label TimeText; //UI компоненты --> //private Label CordsMoText; //private Label CordsRTLSText; //private Label PointText; //private Label TimeLabel; //private Label OtmetkaName; //private Label FullTime; //private Label SlidBegin; //private Label SlidEnd; //private ProgressBar ProgressBar; //private Button PlayButton; //private Button StopButton; //private Button BackButton; //private Slider Slider; //private SliderInt SliderTime; //private SliderInt SliderMove; // <-- UI компоненты [SerializeField] private GameObject MoPointPrefab; //Префаб точки МО [SerializeField] private GameObject RTLSPointPrefab; //Префаб точки РТЛС [Header("UIDocument")] public UIDocument UI; //UI private GameObject moPoint; //память о точке МО private GameObject rtlsPoint; //память о точке РТЛС [Header("Данные ИИ")] public float WaitTime; //Время проверки точки public float NavAgentSpeed; //Скорость перемещения ИИ public Vector3 VectorDestination; //Точка назначения public float RemainingDistance; // оставшееся расстояние до точки [Space] public bool Play; //Проигрывание хождения public void InitMePlease() //Инициализация UI и установка начальных значений { // Спавн точек //if (SceneParams.Instance.spawnMovePoint.IsSpawnMTEPoint) //{ // if (moPoint == null) // { // moPoint = Instantiate(MoPointPrefab, Delogger.LocationsMO[CurrentPoint], MoPointPrefab.gameObject.transform.rotation); //Спавн точки МО // } // else if (moPoint.transform.position != Delogger.LocationsMO[CurrentPoint]) // { // Destroy(moPoint); //Удаление точки МО // } //} //if (SceneParams.Instance.spawnMovePoint.IsSpawnRTLSPoint) //{ // if (rtlsPoint == null) // { // rtlsPoint = Instantiate(RTLSPointPrefab, Delogger.LocationsRTLS[CurrentPoint], MoPointPrefab.gameObject.transform.rotation); //Спавн точки РТЛС // } // else if (rtlsPoint.transform.position != Delogger.LocationsRTLS[CurrentPoint]) // { // Destroy(rtlsPoint); //Удаление точки РТЛС // } //} //Play = true; //Запуск цикла на проверку точки Uiika.EventCurrentDateTimeChanged.AddListener(HandleNewTime); //StartCoroutine("CheckPosition"); } static readonly DateTime defaultDateTime = new DateTime(0); DateTime currentKey = defaultDateTime; TagRecord tagRecordOld; TagRecord? tagRecordNew; DateTime findedKey; DateTime findedKeyNext; public int IsSecondInAnyRange(double second) { var items = Delogger.MarksHronology; // Используем бинарный поиск для нахождения подходящего диапазона int left = 0; int right = items.Count - 1; while (left <= right) { int mid = left + (right - left) / 2; // Проверяем, входит ли second в текущий диапазон if (second >= items[mid].time_start && second <= items[mid].time_end) { return mid; } // Если second меньше time_start, ищем в левой части if (second < items[mid].time_start) { right = mid - 1; } else // Иначе ищем в правой части { left = mid + 1; } } return -1; // Диапазон не найден } public void HandleNewTime(DateTimeChangedData data) { teleportationChecker.KSpeed = data.Speed; NavMeshAgent.speed = teleportationChecker.Speed; var keys = new List(Delogger.mapDateTimeRecords.Keys); DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(data.NewTime); int? keyIndex = FindClosestDateTimeKeyIndex(keys, utcTime); if (keyIndex == null) { // Устанавливаем начальную позицию тэга NavMeshAgent.Warp(SceneParams.Instance.person.StartPosition); currentKey = defaultDateTime; //this.NoSignalCanvas.gameObject.SetActive(true); Uiika.SetMarkText(""); } else { int currentIndex = (int)keyIndex; findedKey = keys[currentIndex]; if (currentKey != findedKey) { currentKey = findedKey; tagRecordOld = Delogger.mapDateTimeRecords[findedKey]; // Перемещаем if (currentIndex == keys.Count - 1) { tagRecordNew = null; // На последний телепортируем NavMeshAgent.Warp(tagRecordOld.LocationsMO); } else { findedKeyNext = keys[currentIndex + 1]; tagRecordNew = Delogger.mapDateTimeRecords[findedKeyNext]; TeleportationChecker.TypeMove typeMove = teleportationChecker.IsNeedWarp(tagRecordOld.LocationsMO, findedKey, tagRecordNew.Value.LocationsMO, findedKeyNext, data.DeltaTime, utcTime, out Vector3 warpPosition); switch (typeMove) { case TeleportationChecker.TypeMove.Move: NavMeshAgent.SetDestination(warpPosition); break; case TeleportationChecker.TypeMove.Warp: NavMeshAgent.Warp(warpPosition); break; } } //if (teleportationChecker.) CheckPoints(tagRecordOld); //Uiika.SetMarkText(tagRecordOld.BlockNamesAliases); int idxRange = IsSecondInAnyRange((data.NewTime - Uiika.DatBegin).TotalSeconds); if (idxRange !=-1) { Uiika.SetMarkText(Delogger.MarksHronology[idxRange].name); } else { Uiika.SetMarkText(""); } } else { if (tagRecordNew != null ) { TeleportationChecker.TypeMove typeMove = teleportationChecker.IsNeedWarp(tagRecordOld.LocationsMO, findedKey, tagRecordNew.Value.LocationsMO, findedKeyNext, data.DeltaTime, utcTime, out Vector3 warpPosition); switch (typeMove) { case TeleportationChecker.TypeMove.Move: NavMeshAgent.SetDestination(warpPosition); break; } } } } } TeleportationChecker teleportationChecker; void Start() { SceneParams.Instance.person.StartPosition = transform.position; teleportationChecker = new TeleportationChecker(NavMeshAgent); } static DateTime? FindClosestDateTime(List keys, DateTime targetDateTime) { // Получаем массив ключей DateTime universalDateTime = targetDateTime.ToUniversalTime(); DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(targetDateTime); // Выполняем бинарный поиск int index = keys.BinarySearch(utcTime); // Если элемент найден, возвращаем предыдущий элемент if (index >= 0) { if (index > 0) { return keys[index - 1]; // Возвращаем предыдущий элемент } else { return null; // Нет элементов меньше заданного } } else { // Если элемент не найден, BinarySearch возвращает отрицательное значение, // которое указывает на место, где элемент мог бы быть вставлен. index = ~index; // Получаем индекс вставки if (index > 0) { return keys[index - 1]; // Возвращаем предыдущий элемент } else { return null; // Нет элементов меньше заданного } } } static int? FindClosestDateTimeKeyIndex(List keys, DateTime targetDateTime) { // Преобразуем целевую дату и время в UTC // Выполняем бинарный поиск int index = keys.BinarySearch(targetDateTime); // Если элемент найден, возвращаем его индекс if (index >= 0) { return index; // Возвращаем индекс найденного элемента } else { // Если элемент не найден, BinarySearch возвращает отрицательное значение, // которое указывает на место, где элемент мог бы быть вставлен. index = ~index; // Получаем индекс вставки if (index > 0) { return index - 1; // Возвращаем индекс предыдущего элемента } else { return null; // Нет элементов меньше заданного } } } void Update() { //if (Play) //{ // RemainingDistance = NavMeshAgent.remainingDistance; //Вывод оставшееся расстояния до точки // NavMeshAgent.SetDestination(Delogger.LocationsMO[CurrentPoint]); //Выставление точки для ИИ в зависимости от текущего индекса // VectorDestination = Delogger.LocationsMO[CurrentPoint]; //Запись координат в переменную для просмотра // CheckPoints(); //Проверка точек есть ли они // //SetUIParams(); //Установление параметров в UI PersonAnimator.SetBool("isMoving", NavMeshAgent.velocity.magnitude > 0.01f); //Проверка скорости ИИ для отображения анимации NavAgentSpeed = NavMeshAgent.velocity.magnitude; //Текущая скорость ИИ //} } //IEnumerator CheckPosition() //{ // if (NavMeshAgent.remainingDistance <= NavMeshAgent.stoppingDistance & Play & CurrentPoint != Delogger.LocationsMO.Count -1) // Проверка на оставшиееся расстояние, на разрешено ли проигрывание, на то что текущая точка не последняя // { // CurrentPoint++; //Следующая точка // } // yield return new WaitForSecondsRealtime(WaitTime); // StartCoroutine("CheckPosition"); //} private void CheckPoints(TagRecord record) { if (SceneParams.Instance.spawnMovePoint.IsSpawnMTEPoint) { if (moPoint == null) { moPoint = Instantiate(MoPointPrefab, record.LocationsMO, MoPointPrefab.gameObject.transform.rotation); //Спавн точки МО } else if (moPoint.transform.position != record.LocationsMO) { Destroy(moPoint); //Удаление точки МО } } if (SceneParams.Instance.spawnMovePoint.IsSpawnRTLSPoint) { if (rtlsPoint == null) { rtlsPoint = Instantiate(RTLSPointPrefab, record.LocationsRTLS, MoPointPrefab.gameObject.transform.rotation); //Спавн точки РТЛС } else if (rtlsPoint.transform.position != record.LocationsRTLS) { Destroy(rtlsPoint); //Удаление точки РТЛС } } } //private void SetUIParams() //{ // SliderTime.SetValueWithoutNotify(CurrentPoint); // TimeText.text = "Время: " + Delogger.Time[CurrentPoint]; // CordsMoText.text = "Координаты МО: " + Delogger.LocationsMO[CurrentPoint]; // CordsRTLSText.text = "Координаты РТЛС: " + Delogger.LocationsRTLS[CurrentPoint]; // PointText.text = "Текущая точка: " + CurrentPoint + " из " + (Delogger.LocationsMO.Count - 1); // string[] strArray = Delogger.Time[CurrentPoint].Split(' '); // TimeLabel.text = strArray[1]; // OtmetkaName.text = Delogger.BlockNamesAliases[CurrentPoint]; //} }