Scripts/PersonScript.cs
Станислав Хозяенок 6df08a2ee4 реализ от 25.04.2025
2025-04-25 08:33:44 +07:00

518 lines
18 KiB
C#

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<DateTime>(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<DateTime> 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<DateTime> 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];
//}
}