Animated MiSide like text

This commit is contained in:
ThomasCharester committed 2026-11-21 00:23:46 +03:00
1 parent 3678d039e3
commit 39df8b3d76
769 files changed
+263431 -91342

No files matched your search

@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: c4f6108eb6144eb1914a997e0ada6d36
timeCreated: 1794237777
@@ -1,3 +1,6 @@
using Code.Game.OfficeGame.Text;
using Cysharp.Threading.Tasks;
using Reflex.Attributes;
using TinyGoose.Tremble;
using UnityEngine;
@@ -6,11 +9,34 @@ namespace Code.Game.OfficeGame.Entities
[PrefabEntity]
public class TestInteractableEntity : InteractableEntity
{
[SerializeField] private string testText = "Interaction";
[SerializeField] private string testText = "Interaction";
[SerializeField] private Transform textPosition;
private UniTask _textHandle;
private IAnimatedTextService _animatedTextService;
[Inject]
private void Construct(IAnimatedTextService animatedTextService)
{
_animatedTextService = animatedTextService;
}
public override void Interact()
{
Debug.Log(testText);
if (_textHandle.Status != UniTaskStatus.Pending)
_textHandle = _animatedTextService.CreateAnimatedText(
testText,
1,
1,
3,
Color.mediumAquamarine,
textPosition.position,
textPosition.rotation,
TextAppearType.Pop,
TextDisappearType.Shrink,
behaviourType: TextBehaviourType.RotateHorizontal);
}
}
}
+3
View File
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7272a3aa1f7a4830894e736f54159dac
timeCreated: 1795192510
@@ -0,0 +1,262 @@
using System;
using System.Threading;
using Code.Infrastructure.Camera;
using Code.Infrastructure.Configs;
using Code.Infrastructure.UI;
using Cysharp.Text;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.Pool;
using UnityEngine.ResourceManagement.AsyncOperations;
namespace Code.Game.OfficeGame.Text
{
public interface IAnimatedTextService
{
UniTask CreateAnimatedText(
string text,
float letterLeadDuration,
float letterDissolveDuration,
float letterLifetime,
Color color,
Vector3 position,
Quaternion rotation,
TextAppearType appearType = TextAppearType.Dissolve,
TextDisappearType disappearType = TextDisappearType.Dissolve,
Vector2? textRectSize = null,
float? letterDelay = null,
TextBehaviourType behaviourType = TextBehaviourType.Steel,
CancellationToken ct = default);
// Zero-Allocation перегрузка для ZString (Utf16ValueStringBuilder)
UniTask CreateAnimatedText(
ref Utf16ValueStringBuilder textBuilder,
float letterLeadDuration,
float letterDissolveDuration,
float letterLifetime,
Color color,
Vector3 position,
Quaternion rotation,
TextAppearType appearType = TextAppearType.Dissolve,
TextDisappearType disappearType = TextDisappearType.Dissolve,
Vector2? textRectSize = null,
float? letterDelay = null,
TextBehaviourType behaviourType = TextBehaviourType.Steel,
CancellationToken ct = default);
// Zero-Allocation перегрузка для форматирования (при желании легко расширить до T2, T3)
UniTask CreateAnimatedTextFormat<T1>(
string format,
T1 arg1,
float letterLeadDuration,
float letterDissolveDuration,
float letterLifetime,
Color color,
Vector3 position,
Quaternion rotation,
TextAppearType appearType = TextAppearType.Dissolve,
TextDisappearType disappearType = TextDisappearType.Dissolve,
Vector2? textRectSize = null,
float? letterDelay = null,
TextBehaviourType behaviourType = TextBehaviourType.Steel,
CancellationToken ct = default);
}
public interface IAnimatedTextServiceInitializer
{
UniTask LoadConfigs();
}
public class AnimatedTextService : IAnimatedTextService, IAnimatedTextServiceInitializer, IDisposable
{
private readonly IUIFactory _uiFactory;
private readonly AssetReference _settingsReference;
private readonly CancellationTokenSource _disposeCts = new();
private AsyncOperationHandle<AnimatedTextSettings> _settingsHandle;
private AsyncOperationHandle<GameObject> _prefabHandle;
private AnimatedTextSettings _settings;
private AnimatedTextView _prefab;
private ObjectPool<AnimatedTextView> _pool;
private CameraStateMachine _cameraStateMachine;
public AnimatedTextService(IUIFactory uiFactory, IConfigLocator configLocator, CameraStateMachine cameraStateMachine)
{
_cameraStateMachine = cameraStateMachine;
_uiFactory = uiFactory;
_settingsReference = configLocator.TryGetConfigAssetReference<AnimatedTextSettings>();
}
// Вызывайте после UIFactoryInitializer.LoadConfigs(), когда GameplayCanvas уже создан
public async UniTask LoadConfigs()
{
_settingsHandle = Addressables.LoadAssetAsync<AnimatedTextSettings>(_settingsReference);
_settings = await _settingsHandle.ToUniTask();
_prefabHandle = Addressables.LoadAssetAsync<GameObject>(_settings.TextPrefab);
var prefabGo = await _prefabHandle.ToUniTask();
_prefab = prefabGo.GetComponent<AnimatedTextView>();
_pool = new ObjectPool<AnimatedTextView>(
createFunc: CreatePooledView,
actionOnGet: view => view.gameObject.SetActive(true),
actionOnRelease: view =>
{
view.ResetState();
view.gameObject.SetActive(false);
},
actionOnDestroy: view =>
{
if (view)
UnityEngine.Object.Destroy(view.gameObject);
},
collectionCheck: false,
defaultCapacity: _settings.InitialPoolCapacity,
maxSize: _settings.MaxPoolSize);
}
public UniTask CreateAnimatedText(
string text,
float letterLeadDuration,
float letterDissolveDuration,
float letterLifetime,
Color color,
Vector3 position,
Quaternion rotation,
TextAppearType appearType = TextAppearType.Dissolve,
TextDisappearType disappearType = TextDisappearType.Dissolve,
Vector2? textRectSize = null,
float? letterDelay = null,
TextBehaviourType behaviourType = TextBehaviourType.Steel,
CancellationToken ct = default)
{
var view = AcquireAndConfigureView(position, rotation, textRectSize);
view.SetText(text);
return RunAndReleaseAsync(
view, letterLeadDuration, letterDissolveDuration, letterLifetime,
letterDelay ?? _settings.DefaultLetterDelay, color, appearType, disappearType, behaviourType, ct);
}
// Без модификатора async: буфер ZString копируется в TMP_Text синхронно до старта ожидания,
// поэтому вызывающий код может сразу освободить sb через using!
public UniTask CreateAnimatedText(
ref Utf16ValueStringBuilder textBuilder,
float letterLeadDuration,
float letterDissolveDuration,
float letterLifetime,
Color color,
Vector3 position,
Quaternion rotation,
TextAppearType appearType = TextAppearType.Dissolve,
TextDisappearType disappearType = TextDisappearType.Dissolve,
Vector2? textRectSize = null,
float? letterDelay = null,
TextBehaviourType behaviourType = TextBehaviourType.Steel,
CancellationToken ct = default)
{
var view = AcquireAndConfigureView(position, rotation, textRectSize);
view.SetText(ref textBuilder);
return RunAndReleaseAsync(
view, letterLeadDuration, letterDissolveDuration, letterLifetime,
letterDelay ?? _settings.DefaultLetterDelay, color, appearType, disappearType, behaviourType, ct);
}
public UniTask CreateAnimatedTextFormat<T1>(
string format,
T1 arg1,
float letterLeadDuration,
float letterDissolveDuration,
float letterLifetime,
Color color,
Vector3 position,
Quaternion rotation,
TextAppearType appearType = TextAppearType.Dissolve,
TextDisappearType disappearType = TextDisappearType.Dissolve,
Vector2? textRectSize = null,
float? letterDelay = null,
TextBehaviourType behaviourType = TextBehaviourType.Steel,
CancellationToken ct = default)
{
var view = AcquireAndConfigureView(position, rotation, textRectSize);
view.SetTextFormat(format, arg1);
return RunAndReleaseAsync(
view, letterLeadDuration, letterDissolveDuration, letterLifetime,
letterDelay ?? _settings.DefaultLetterDelay, color, appearType, disappearType, behaviourType, ct);
}
private AnimatedTextView AcquireAndConfigureView(Vector3 position, Quaternion rotation, Vector2? textRectSize)
{
var view = _pool.Get();
view.ConfigureTransform(position, rotation, textRectSize ?? _settings.DefaultRectSize);
return view;
}
private async UniTask RunAndReleaseAsync(
AnimatedTextView view,
float letterLeadDuration,
float letterDissolveDuration,
float letterLifetime,
float letterDelay,
Color color,
TextAppearType appearType,
TextDisappearType disappearType,
TextBehaviourType behaviourType,
CancellationToken ct)
{
try
{
if (ct.CanBeCanceled)
{
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(ct, _disposeCts.Token);
await view.PlayAsync(
letterLeadDuration, letterDissolveDuration, letterLifetime, letterDelay,
color, appearType, disappearType,
_settings.FallDistance, _settings.MaxFallRotationAngle, behaviourType, linkedCts.Token);
}
else
{
await view.PlayAsync(
letterLeadDuration, letterDissolveDuration, letterLifetime, letterDelay,
color, appearType, disappearType,
_settings.FallDistance, _settings.MaxFallRotationAngle, behaviourType, _disposeCts.Token);
}
}
finally
{
if (view)
{
_pool.Release(view);
}
}
}
private AnimatedTextView CreatePooledView()
{
var instance = UnityEngine.Object.Instantiate(_prefab, _uiFactory.GameplayCanvas.transform);
instance.gameObject.SetActive(false);
instance.SetTarget(_cameraStateMachine.Camera.transform);
return instance;
}
public void Dispose()
{
_disposeCts.Cancel();
_disposeCts.Dispose();
_pool?.Clear();
if (_prefabHandle.IsValid())
Addressables.Release(_prefabHandle);
if (_settingsHandle.IsValid())
Addressables.Release(_settingsHandle);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 785d5be8f28747f3b24abdf30577e18b
timeCreated: 1795198692
@@ -0,0 +1,25 @@
using Code.Infrastructure.Generators;
using TMPro;
using UnityEngine;
using UnityEngine.AddressableAssets;
namespace Code.Game.OfficeGame.Text
{
[CreateAssetMenu(fileName = "AnimatedTextSettings", menuName = "Configs/UI/AnimatedTextSettings")]
[Config("Configs/UI/AnimatedTextSettings")]
public class AnimatedTextSettings : ScriptableObject
{
[Tooltip("Префаб с компонентами TMP_Text и AnimatedTextView")]
public AssetReference TextPrefab;
[Header("Default Layout")]
public Vector2 DefaultRectSize = new(4f, 1.5f); // Подберите под масштаб вашего WorldSpace Canvas
[Header("Default Animation")] public float DefaultLetterDelay = 0.04f;
public float FallDistance = 0.8f; // Смещение в локальных единицах TMP_Text
public float MaxFallRotationAngle = 25f;
[Header("Pool")] public int InitialPoolCapacity = 16;
public int MaxPoolSize = 64;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d9897081f7a1499cb7041e707b93207c
timeCreated: 1795192571
@@ -0,0 +1,297 @@
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<TMP_Text>();
_rectTransform = GetComponent<RectTransform>();
}
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<T1>(string format, T1 arg1)
{
_text.SetTextFormat(format, arg1);
}
public void SetTextFormat<T1, T2>(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();
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f18340113778408489d5fbb20b1632b8
timeCreated: 1795192626
@@ -0,0 +1,25 @@
namespace Code.Game.OfficeGame.Text
{
public enum TextAppearType
{
Dissolve, // Плавное проявление (альфа 0 -> 1)
Fall, // Падение сверху + проявление
Rise, // Вылет снизу + проявление
Pop // Появление через масштаб (0 -> 1 с OutBack)
}
public enum TextDisappearType
{
Dissolve, // Плавное растворение (альфа 1 -> 0)
Fall, // Падение вниз с ускорением, случайным вращением и растворением
Rise, // Улёт вверх и растворение
Shrink // Схлопывание (scale 1 -> 0)
}
public enum TextBehaviourType
{
Steel,
RotateHorizontal,
Rotate
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 18d87f8b17d946e2a414249fb6bc483c
timeCreated: 1795192536