using System.Threading; using Code.OfficeGame.BattleMode.Actions; using Cysharp.Text; using Cysharp.Threading.Tasks; using LitMotion; using LitMotion.Extensions; using TMPro; using UnityEngine; using DelayType = LitMotion.DelayType; namespace Code.Game.OfficeGame.Text { [RequireComponent(typeof(TMP_Text))] public class AnimatedTextView : MonoBehaviour { [SerializeField] private TMP_Text _text; [SerializeField] private RectTransform _rectTransform; private readonly CompositeMotionHandle _handles = new(); private Transform _targetTransform; private bool _canRotate = false; private bool _onlyYAxis = false; public void SetTarget(Transform player) { _targetTransform = player; } private void LateUpdate() { if (!_targetTransform || !_canRotate) return; Vector3 direction = transform.position - _targetTransform.position; if (_onlyYAxis) { direction.y = 0f; } if (direction.sqrMagnitude > 0.0001f) { transform.rotation = Quaternion.LookRotation(direction); } } private void Reset() { _text = GetComponent(); _rectTransform = GetComponent(); } public void ConfigureTransform(Vector3 worldPosition, Quaternion rotation, Vector2 rectSize) { _rectTransform.position = worldPosition; _rectTransform.rotation = rotation; _rectTransform.sizeDelta = rectSize; // _rectTransform.localScale = Vector3.one; } // Обычная строка (подходит для констант/локализованных строк) public void SetText(string text) { _text.SetText(text); } // Zero-Allocation запись напрямую из буфера ZString в TMP_Text public void SetText(ref Utf16ValueStringBuilder sb) { _text.SetText(sb); } // Zero-Allocation форматирование через ZString public void SetTextFormat(string format, T1 arg1) { _text.SetTextFormat(format, arg1); } public void SetTextFormat(string format, T1 arg1, T2 arg2) { _text.SetTextFormat(format, arg1, arg2); } public async UniTask PlayAsync( float letterLeadDuration, float letterDissolveDuration, float letterLifetime, float letterDelay, Color color, TextAppearType appearType, TextDisappearType disappearType, float fallDistance, float maxRotationAngle, TextBehaviourType behaviourType, CancellationToken ct) { switch (behaviourType) { case TextBehaviourType.Steel: _canRotate = false; break; case TextBehaviourType.RotateHorizontal: _canRotate = true; _onlyYAxis = true; break; case TextBehaviourType.Rotate: _canRotate = true; _onlyYAxis = false; break; } _handles.Cancel(); _text.color = color; _text.ForceMeshUpdate(); var textInfo = _text.textInfo; int charCount = textInfo.characterCount; if (charCount == 0) return; float leadDuration = Mathf.Max(0.001f, letterLeadDuration); float dissolveDuration = Mathf.Max(0.001f, letterDissolveDuration); var transparentColor = new Color(color.r, color.g, color.b, 0f); int visibleIndex = 0; MotionHandle lastHandle = MotionHandle.None; for (int i = 0; i < charCount; i++) { if (!textInfo.characterInfo[i].isVisible) continue; float appearDelay = visibleIndex * letterDelay; float disappearDelay = appearDelay + leadDuration + letterLifetime; AddAppearMotions(i, appearDelay, leadDuration, color, transparentColor, appearType, fallDistance); lastHandle = AddDisappearMotions( i, disappearDelay, dissolveDuration, color, transparentColor, disappearType, fallDistance, maxRotationAngle); visibleIndex++; } if (!lastHandle.IsActive()) return; // Ожидаем завершения последнего символа. // Если передан внешний токен — связываем его с destroyCancellationToken, иначе избегаем аллокации CTS. if (ct.CanBeCanceled) { using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(ct, destroyCancellationToken); await UniTask .WaitForSeconds( leadDuration + letterLifetime, true, cancellationToken: linkedCts.Token); _canRotate = false; await lastHandle.ToUniTask(cancellationToken: linkedCts.Token).SuppressCancellationThrow(); } else { await UniTask .WaitForSeconds( leadDuration + letterLifetime, true, cancellationToken: destroyCancellationToken); _canRotate = false; await lastHandle.ToUniTask(cancellationToken: destroyCancellationToken).SuppressCancellationThrow(); } } private void AddAppearMotions( int charIndex, float delay, float duration, Color targetColor, Color transparentColor, TextAppearType appearType, float fallDistance) { // skipValuesDuringDelay: false — буква с первого кадра держит стартовое состояние до своей очереди LMotion.Create(transparentColor, targetColor, duration) .WithDelay(delay, DelayType.FirstLoop, skipValuesDuringDelay: false) .WithEase(Ease.OutQuad) .BindToTMPCharColor(_text, charIndex) .AddTo(_handles); switch (appearType) { case TextAppearType.Fall: LMotion.Create(new Vector3(0f, fallDistance, 0f), Vector3.zero, duration) .WithDelay(delay, DelayType.FirstLoop, skipValuesDuringDelay: false) .WithEase(Ease.OutCubic) .BindToTMPCharPosition(_text, charIndex) .AddTo(_handles); break; case TextAppearType.Rise: LMotion.Create(new Vector3(0f, -fallDistance, 0f), Vector3.zero, duration) .WithDelay(delay, DelayType.FirstLoop, skipValuesDuringDelay: false) .WithEase(Ease.OutCubic) .BindToTMPCharPosition(_text, charIndex) .AddTo(_handles); break; case TextAppearType.Pop: LMotion.Create(Vector3.zero, Vector3.one, duration) .WithDelay(delay, DelayType.FirstLoop, skipValuesDuringDelay: false) .WithEase(Ease.OutBack) .BindToTMPCharScale(_text, charIndex) .AddTo(_handles); break; case TextAppearType.Dissolve: default: break; } } private MotionHandle AddDisappearMotions( int charIndex, float delay, float duration, Color startColor, Color transparentColor, TextDisappearType disappearType, float fallDistance, float maxRotationAngle) { // skipValuesDuringDelay: true — не мешает анимации появления и времени жизни буквы var colorHandle = LMotion.Create(startColor, transparentColor, duration) .WithDelay(delay, DelayType.FirstLoop, skipValuesDuringDelay: true) .WithEase(Ease.InQuad) .BindToTMPCharColor(_text, charIndex) .AddTo(_handles); switch (disappearType) { case TextDisappearType.Fall: LMotion.Create(Vector3.zero, new Vector3(0f, -fallDistance, 0f), duration) .WithDelay(delay, DelayType.FirstLoop, skipValuesDuringDelay: true) .WithEase(Ease.InQuad) .BindToTMPCharPosition(_text, charIndex) .AddTo(_handles); float randomAngle = Random.Range(-maxRotationAngle, maxRotationAngle); LMotion.Create(Vector3.zero, new Vector3(0f, 0f, randomAngle), duration) .WithDelay(delay, DelayType.FirstLoop, skipValuesDuringDelay: true) .WithEase(Ease.InQuad) .BindToTMPCharEulerAngles(_text, charIndex) .AddTo(_handles); break; case TextDisappearType.Rise: LMotion.Create(Vector3.zero, new Vector3(0f, fallDistance, 0f), duration) .WithDelay(delay, DelayType.FirstLoop, skipValuesDuringDelay: true) .WithEase(Ease.InCubic) .BindToTMPCharPosition(_text, charIndex) .AddTo(_handles); break; case TextDisappearType.Shrink: LMotion.Create(Vector3.one, Vector3.zero, duration) .WithDelay(delay, DelayType.FirstLoop, skipValuesDuringDelay: true) .WithEase(Ease.InBack) .BindToTMPCharScale(_text, charIndex) .AddTo(_handles); break; case TextDisappearType.Dissolve: default: break; } return colorHandle; } public void ResetState() { _handles.Cancel(); _text.SetText(string.Empty); _text.ForceMeshUpdate(); } private void OnDestroy() { _handles.Cancel(); } } }