Great timeline system (Age of AI WON)
This commit is contained in:
1 parent
2ce0391c16
commit
e312131725
182 files changed
+380070
-470221
No files matched your search
@@ -5,178 +5,239 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
{
|
||||
public class EntityPreviewVisuals : MonoBehaviour
|
||||
{
|
||||
[Header("Материалы для MKToon")]
|
||||
[Tooltip("Полупрозрачный материал для статичного слепка в точке снапшота")]
|
||||
[SerializeField]
|
||||
private Material snapshotGhostMaterial;
|
||||
public const int MaxGhostStages = 5; // 0 = Commit + до 4 прерываний
|
||||
|
||||
[Tooltip(
|
||||
"Опционально: материал для самой движущейся модели во время превью (если null — меняется только Rim/Tint)")]
|
||||
[SerializeField]
|
||||
private Material activePreviewMaterial;
|
||||
[Header("Материалы MKToon")]
|
||||
[SerializeField] private Material snapshotGhostMaterial;
|
||||
[SerializeField] private Material activePreviewMaterial;
|
||||
|
||||
[Header("Настройки подсветки MKToon (если activePreviewMaterial не задан)")] [SerializeField]
|
||||
private Color previewAlbedoTint = new Color(0.6f, 0.85f, 1f, 1f);
|
||||
[Header("Цвета проекции по стадиям прерываний")]
|
||||
[SerializeField] private Color[] stageProjectionTints =
|
||||
{
|
||||
new(0.55f, 0.85f, 1.0f, 1f), // Stage 0: до первого прерывания (голубой)
|
||||
new(1.0f, 0.85f, 0.35f, 1f), // Stage 1: после 1-го прерывания (жёлтый)
|
||||
new(1.0f, 0.55f, 0.25f, 1f), // Stage 2: после 2-го прерывания (оранжевый)
|
||||
new(0.95f, 0.3f, 0.5f, 1f), // Stage 3+: 3+ прерываний (малиновый)
|
||||
};
|
||||
|
||||
[SerializeField, ColorUsage(true, true)]
|
||||
private Color previewRimColor = new Color(0f, 1.5f, 2f, 1f);
|
||||
[Header("Цвета статичных слепков")]
|
||||
[SerializeField] private Color defaultGhostTint = new(0.6f, 0.85f, 1f, 0.35f);
|
||||
[SerializeField] private Color completedActorGhostColor = new(0.2f, 1f, 0.45f, 0.65f);
|
||||
|
||||
private sealed class GhostSlot
|
||||
{
|
||||
public GameObject Root;
|
||||
public Mesh[] BakedMeshes;
|
||||
public MeshFilter[] Filters;
|
||||
public MeshRenderer[] Renderers;
|
||||
public int TriggerFrame = int.MaxValue;
|
||||
public bool IsActiveInBake;
|
||||
}
|
||||
|
||||
private SkinnedMeshRenderer[] _skinnedRenderers;
|
||||
private MeshRenderer[] _meshRenderers;
|
||||
|
||||
// Кэш оригинальных материалов
|
||||
private readonly Dictionary<Renderer, Material[]> _originalMaterials = new();
|
||||
|
||||
// Пул объектов для статичного слепка (чтобы не делать Instantiate и new Mesh каждый цикл превью)
|
||||
private GameObject _snapshotGhostRoot;
|
||||
private readonly List<Mesh> _bakedMeshes = new();
|
||||
private readonly List<MeshFilter> _ghostMeshFilters = new();
|
||||
private readonly List<MeshRenderer> _ghostMeshRenderers = new();
|
||||
private GhostSlot[] _ghostSlots;
|
||||
|
||||
private MaterialPropertyBlock _propBlock;
|
||||
private static readonly int AlbedoColorId = Shader.PropertyToID("_AlbedoColor");
|
||||
private static readonly int BaseColorId = Shader.PropertyToID("_BaseColor");
|
||||
private static readonly int RimColorId = Shader.PropertyToID("_RimColor");
|
||||
|
||||
private bool _isPreviewLookApplied;
|
||||
private int _currentAppliedStage = -1;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
_propBlock = new MaterialPropertyBlock();
|
||||
_skinnedRenderers = GetComponentsInChildren<SkinnedMeshRenderer>();
|
||||
_meshRenderers = GetComponentsInChildren<MeshRenderer>();
|
||||
|
||||
// Сохраняем родные материалы MKToon
|
||||
foreach (var sr in _skinnedRenderers)
|
||||
_originalMaterials[sr] = sr.sharedMaterials;
|
||||
|
||||
foreach (var mr in _meshRenderers)
|
||||
_originalMaterials[mr] = mr.sharedMaterials;
|
||||
foreach (var sr in _skinnedRenderers) _originalMaterials[sr] = sr.sharedMaterials;
|
||||
foreach (var mr in _meshRenderers) _originalMaterials[mr] = mr.sharedMaterials;
|
||||
|
||||
InitializeGhostPool();
|
||||
}
|
||||
|
||||
private void InitializeGhostPool()
|
||||
{
|
||||
_snapshotGhostRoot = new GameObject($"{gameObject.name}_SnapshotGhost");
|
||||
_snapshotGhostRoot.SetActive(false);
|
||||
_ghostSlots = new GhostSlot[MaxGhostStages];
|
||||
|
||||
for (int s = 0; s < MaxGhostStages; s++)
|
||||
{
|
||||
var root = new GameObject($"{gameObject.name}_GhostStage_{s}");
|
||||
root.SetActive(false);
|
||||
|
||||
int count = _skinnedRenderers.Length;
|
||||
var slot = new GhostSlot
|
||||
{
|
||||
Root = root,
|
||||
BakedMeshes = new Mesh[count],
|
||||
Filters = new MeshFilter[count],
|
||||
Renderers = new MeshRenderer[count]
|
||||
};
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var partGo = new GameObject($"Part_{i}");
|
||||
partGo.transform.SetParent(root.transform, false);
|
||||
|
||||
var mf = partGo.AddComponent<MeshFilter>();
|
||||
var mr = partGo.AddComponent<MeshRenderer>();
|
||||
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
|
||||
|
||||
var mesh = new Mesh { name = $"BakedGhost_{s}_{i}" };
|
||||
mf.sharedMesh = mesh;
|
||||
|
||||
slot.BakedMeshes[i] = mesh;
|
||||
slot.Filters[i] = mf;
|
||||
slot.Renderers[i] = mr;
|
||||
}
|
||||
|
||||
_ghostSlots[s] = slot;
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearAllGhosts()
|
||||
{
|
||||
if (_ghostSlots == null) return;
|
||||
foreach (var slot in _ghostSlots)
|
||||
{
|
||||
slot.IsActiveInBake = false;
|
||||
slot.TriggerFrame = int.MaxValue;
|
||||
if (slot.Root != null) slot.Root.SetActive(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Запекает статичный слепок во время BakeFrom (в точке Commit или в точке прерывания).
|
||||
/// </summary>
|
||||
public void BakeGhostAtStage(int stageIndex, int triggerFrame, bool isCompletingActor)
|
||||
{
|
||||
if (snapshotGhostMaterial == null || stageIndex < 0 || stageIndex >= MaxGhostStages)
|
||||
return;
|
||||
|
||||
var slot = _ghostSlots[stageIndex];
|
||||
slot.TriggerFrame = triggerFrame;
|
||||
slot.IsActiveInBake = true;
|
||||
slot.Root.transform.SetPositionAndRotation(transform.position, transform.rotation);
|
||||
|
||||
Color ghostColor = isCompletingActor
|
||||
? completedActorGhostColor
|
||||
: GetStageColor(stageIndex, alphaOverride: defaultGhostTint.a);
|
||||
|
||||
// Создаём легковесные меш-объекты под каждый SkinnedMeshRenderer персонажа
|
||||
for (int i = 0; i < _skinnedRenderers.Length; i++)
|
||||
{
|
||||
var partGo = new GameObject($"GhostPart_{i}");
|
||||
partGo.transform.SetParent(_snapshotGhostRoot.transform, false);
|
||||
var sr = _skinnedRenderers[i];
|
||||
sr.BakeMesh(slot.BakedMeshes[i]);
|
||||
|
||||
var mf = partGo.AddComponent<MeshFilter>();
|
||||
var mr = partGo.AddComponent<MeshRenderer>();
|
||||
var ghostTransform = slot.Filters[i].transform;
|
||||
ghostTransform.SetPositionAndRotation(sr.transform.position, sr.transform.rotation);
|
||||
|
||||
// Отключаем тени у призрака для чистоты картинки и производительности
|
||||
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
|
||||
int subMeshCount = Mathf.Max(1, slot.BakedMeshes[i].subMeshCount);
|
||||
var mats = new Material[subMeshCount];
|
||||
for (int m = 0; m < subMeshCount; m++) mats[m] = snapshotGhostMaterial;
|
||||
slot.Renderers[i].sharedMaterials = mats;
|
||||
|
||||
var bakedMesh = new Mesh { name = $"BakedGhostMesh_{i}" };
|
||||
mf.sharedMesh = bakedMesh;
|
||||
|
||||
_bakedMeshes.Add(bakedMesh);
|
||||
_ghostMeshFilters.Add(mf);
|
||||
_ghostMeshRenderers.Add(mr);
|
||||
slot.Renderers[i].GetPropertyBlock(_propBlock);
|
||||
_propBlock.SetColor(AlbedoColorId, ghostColor);
|
||||
_propBlock.SetColor(BaseColorId, ghostColor);
|
||||
slot.Renderers[i].SetPropertyBlock(_propBlock);
|
||||
}
|
||||
|
||||
slot.Root.SetActive(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вызывается перед стартом цикла PreviewBattleLoopAsync (в момент снятия снапшота)
|
||||
/// Синхронизирует видимость слепков и цвет проекции для текущего кадра ползунка.
|
||||
/// Для прошлых кадров (viewFrame <= committedFrame) проекция автоматически выключается!
|
||||
/// </summary>
|
||||
public void ShowPreviewState(bool spawnStaticSnapshotGhost = true)
|
||||
public void UpdateForTimelineFrame(int viewFrame, int committedFrame, int interruptionStage, bool showPreviewVisuals)
|
||||
{
|
||||
// 1. Запекаем полупрозрачную статую в текущей точке снапшота
|
||||
if (spawnStaticSnapshotGhost && snapshotGhostMaterial != null)
|
||||
bool inFuture = showPreviewVisuals && viewFrame > committedFrame;
|
||||
|
||||
if (!inFuture)
|
||||
{
|
||||
_snapshotGhostRoot.transform.SetPositionAndRotation(transform.position, transform.rotation);
|
||||
|
||||
for (int i = 0; i < _skinnedRenderers.Length; i++)
|
||||
{
|
||||
var sr = _skinnedRenderers[i];
|
||||
sr.BakeMesh(_bakedMeshes[i]); // Мгновенный снимок позы скелета!
|
||||
|
||||
var ghostTransform = _ghostMeshFilters[i].transform;
|
||||
ghostTransform.SetPositionAndRotation(sr.transform.position, sr.transform.rotation);
|
||||
// ghostTransform.localScale = sr.transform.lossyScale;
|
||||
|
||||
// Назначаем прозрачный материал на все саб-меши
|
||||
int subMeshCount = _bakedMeshes[i].subMeshCount;
|
||||
Material[] ghostMats = new Material[Mathf.Max(1, subMeshCount)];
|
||||
for (int m = 0; m < ghostMats.Length; m++)
|
||||
ghostMats[m] = snapshotGhostMaterial;
|
||||
|
||||
_ghostMeshRenderers[i].sharedMaterials = ghostMats;
|
||||
}
|
||||
|
||||
_snapshotGhostRoot.SetActive(true);
|
||||
HidePreviewLook();
|
||||
for (int s = 0; s < _ghostSlots.Length; s++)
|
||||
if (_ghostSlots[s].Root.activeSelf) _ghostSlots[s].Root.SetActive(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. Меняем внешний вид самой модели, которая сейчас побежит в превью
|
||||
ApplyPreviewLookToMainModel();
|
||||
ApplyPreviewLook(interruptionStage);
|
||||
|
||||
for (int s = 0; s < _ghostSlots.Length; s++)
|
||||
{
|
||||
var slot = _ghostSlots[s];
|
||||
bool shouldShow = slot.IsActiveInBake && viewFrame > slot.TriggerFrame;
|
||||
if (slot.Root.activeSelf != shouldShow)
|
||||
slot.Root.SetActive(shouldShow);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вызывается в блоке finally в PreviewBattleLoopAsync
|
||||
/// </summary>
|
||||
public void HidePreviewState()
|
||||
{
|
||||
if (_snapshotGhostRoot != null)
|
||||
_snapshotGhostRoot.SetActive(false);
|
||||
|
||||
RestoreMainModelLook();
|
||||
ClearAllGhosts();
|
||||
HidePreviewLook();
|
||||
}
|
||||
|
||||
private void ApplyPreviewLookToMainModel()
|
||||
private void ApplyPreviewLook(int stage)
|
||||
{
|
||||
if (_isPreviewLookApplied && _currentAppliedStage == stage) return;
|
||||
_isPreviewLookApplied = true;
|
||||
_currentAppliedStage = stage;
|
||||
|
||||
Color tint = GetStageColor(stage);
|
||||
|
||||
foreach (var (renderer, origMats) in _originalMaterials)
|
||||
{
|
||||
if (renderer == null) continue;
|
||||
|
||||
// Способ 1: Если задан отдельный материал для превью — подменяем sharedMaterials
|
||||
if (activePreviewMaterial != null)
|
||||
{
|
||||
Material[] previewMats = new Material[origMats.Length];
|
||||
for (int i = 0; i < previewMats.Length; i++)
|
||||
previewMats[i] = activePreviewMaterial;
|
||||
|
||||
var previewMats = new Material[origMats.Length];
|
||||
for (int i = 0; i < previewMats.Length; i++) previewMats[i] = activePreviewMaterial;
|
||||
renderer.sharedMaterials = previewMats;
|
||||
}
|
||||
// Способ 2: Иначе подкрашиваем родной MKToon через MaterialPropertyBlock (без аллокаций)
|
||||
else
|
||||
{
|
||||
renderer.GetPropertyBlock(_propBlock);
|
||||
_propBlock.SetColor(AlbedoColorId, previewAlbedoTint);
|
||||
_propBlock.SetColor(RimColorId, previewRimColor);
|
||||
renderer.SetPropertyBlock(_propBlock);
|
||||
}
|
||||
|
||||
renderer.GetPropertyBlock(_propBlock);
|
||||
_propBlock.SetColor(AlbedoColorId, tint);
|
||||
_propBlock.SetColor(RimColorId, tint * 1.5f);
|
||||
renderer.SetPropertyBlock(_propBlock);
|
||||
}
|
||||
}
|
||||
|
||||
private void RestoreMainModelLook()
|
||||
private void HidePreviewLook()
|
||||
{
|
||||
if (!_isPreviewLookApplied) return;
|
||||
_isPreviewLookApplied = false;
|
||||
_currentAppliedStage = -1;
|
||||
|
||||
foreach (var (renderer, origMats) in _originalMaterials)
|
||||
{
|
||||
if (renderer == null) continue;
|
||||
|
||||
if (activePreviewMaterial != null)
|
||||
{
|
||||
renderer.sharedMaterials = origMats;
|
||||
}
|
||||
else
|
||||
{
|
||||
renderer.SetPropertyBlock(null); // Сбрасывает все переопределения PropertyBlock
|
||||
}
|
||||
if (activePreviewMaterial != null) renderer.sharedMaterials = origMats;
|
||||
renderer.SetPropertyBlock(null);
|
||||
}
|
||||
}
|
||||
|
||||
private Color GetStageColor(int stage, float? alphaOverride = null)
|
||||
{
|
||||
Color c = stageProjectionTints[Mathf.Clamp(stage, 0, stageProjectionTints.Length - 1)];
|
||||
if (alphaOverride.HasValue) c.a = alphaOverride.Value;
|
||||
return c;
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
foreach (var mesh in _bakedMeshes)
|
||||
if (_ghostSlots == null) return;
|
||||
foreach (var slot in _ghostSlots)
|
||||
{
|
||||
if (mesh != null) Destroy(mesh);
|
||||
if (slot == null) continue;
|
||||
foreach (var mesh in slot.BakedMeshes)
|
||||
if (mesh != null) Destroy(mesh);
|
||||
if (slot.Root != null) Destroy(slot.Root);
|
||||
}
|
||||
|
||||
if (_snapshotGhostRoot != null)
|
||||
Destroy(_snapshotGhostRoot);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,66 @@
|
||||
using Code.OfficeGame.BattleMode.Health;
|
||||
using KinematicCharacterController;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Code.OfficeGame.BattleMode.Actions
|
||||
{
|
||||
public struct BonePoseSnapshot
|
||||
{
|
||||
public Vector3[] LocalPositions;
|
||||
public Quaternion[] LocalRotations;
|
||||
|
||||
public static BonePoseSnapshot Capture(Transform[] bones)
|
||||
{
|
||||
if (bones == null || bones.Length == 0)
|
||||
return default;
|
||||
|
||||
int count = bones.Length;
|
||||
var pos = new Vector3[count];
|
||||
var rot = new Quaternion[count];
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
pos[i] = bones[i].localPosition;
|
||||
rot[i] = bones[i].localRotation;
|
||||
}
|
||||
|
||||
return new BonePoseSnapshot
|
||||
{
|
||||
LocalPositions = pos,
|
||||
LocalRotations = rot
|
||||
};
|
||||
}
|
||||
|
||||
public readonly void ApplyTo(Transform[] bones)
|
||||
{
|
||||
if (bones == null || LocalPositions == null) return;
|
||||
|
||||
int count = Mathf.Min(bones.Length, LocalPositions.Length);
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
bones[i].localPosition = LocalPositions[i];
|
||||
bones[i].localRotation = LocalRotations[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public struct EntitySnapshot
|
||||
{
|
||||
// 1. KCC Motor
|
||||
// --- Уровень 1: Визуальный (для O(1) скраббинга ползунком) ---
|
||||
public Vector3 Position;
|
||||
public Quaternion Rotation;
|
||||
public Vector3 BaseVelocity;
|
||||
public BonePoseSnapshot BonePose;
|
||||
public HealthData CurrentHealth;
|
||||
|
||||
// 2. MovementController
|
||||
// --- Уровень 2: Полное состояние симуляции (для BakeFrom) ---
|
||||
public KinematicCharacterMotorState MotorState;
|
||||
public bool IsFrozen;
|
||||
public Vector3 MoveInputVector;
|
||||
public Vector3 LookInputVector;
|
||||
|
||||
// 3. Здоровье
|
||||
public HealthData CurrentHealth;
|
||||
|
||||
// 4. Аниматор
|
||||
public Vector3 InternalVelocityAdd;
|
||||
public AnimatorSnapshot AnimatorSnapshot;
|
||||
|
||||
public static EntitySnapshot GetSnapshot(EntityProperties entity)
|
||||
public static EntitySnapshot GetSnapshot(EntityProperties entity, Transform[] cachedBones)
|
||||
{
|
||||
var motor = entity.KinematicCharacterMotor;
|
||||
var moveCtrl = entity.MovementController;
|
||||
@@ -30,49 +69,52 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
{
|
||||
Position = motor.TransientPosition,
|
||||
Rotation = motor.TransientRotation,
|
||||
BaseVelocity = motor.BaseVelocity,
|
||||
BonePose = BonePoseSnapshot.Capture(cachedBones),
|
||||
CurrentHealth = entity.EntityHealth != null ? entity.EntityHealth.HealthData.CurrentValue : default,
|
||||
|
||||
MotorState = motor.GetState(),
|
||||
IsFrozen = moveCtrl.Freeze,
|
||||
// Сохраните текущие входы контроллера (добавьте публичные геттеры в MovementController, если они приватные)
|
||||
MoveInputVector = moveCtrl.MoveInputVector,
|
||||
LookInputVector = moveCtrl.LookInputVector,
|
||||
|
||||
CurrentHealth = entity.EntityHealth != null ? entity.EntityHealth.HealthData.CurrentValue : default,
|
||||
InternalVelocityAdd = moveCtrl.InternalVelocityAdd,
|
||||
AnimatorSnapshot = AnimatorSnapshot.GetSnapshot(entity.animator)
|
||||
};
|
||||
}
|
||||
|
||||
public static void RestoreSnapshot(EntityProperties entity, EntitySnapshot snapshot)
|
||||
/// <summary>
|
||||
/// Мгновенное O(1) восстановление визуала для ползунка и воспроизведения ленты.
|
||||
/// Не трогает Mecanim и не мутирует EntityHealth.
|
||||
/// </summary>
|
||||
public static void ApplyVisualOnly(EntityProperties entity, Transform[] cachedBones, in EntitySnapshot snapshot)
|
||||
{
|
||||
entity.KinematicCharacterMotor.SetPositionAndRotation(
|
||||
snapshot.Position,
|
||||
snapshot.Rotation,
|
||||
bypassInterpolation: true);
|
||||
|
||||
snapshot.BonePose.ApplyTo(cachedBones);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Полное детерминированное восстановление для старта/перезапекания физической симуляции.
|
||||
/// </summary>
|
||||
public static void RestoreForSimulation(EntityProperties entity, Transform[] cachedBones, in EntitySnapshot snapshot)
|
||||
{
|
||||
var motor = entity.KinematicCharacterMotor;
|
||||
var moveCtrl = entity.MovementController;
|
||||
|
||||
// 1. Восстанавливаем MovementController ДО шага KCC
|
||||
moveCtrl.Freeze = snapshot.IsFrozen;
|
||||
var restoredInputs = new Code.Game.Gameplay.Player.AICharacterInputs
|
||||
{
|
||||
MoveVector = snapshot.MoveInputVector,
|
||||
Look = snapshot.LookInputVector.sqrMagnitude > 0.0001f
|
||||
? Quaternion.LookRotation(snapshot.LookInputVector, motor.CharacterUp)
|
||||
: snapshot.Rotation
|
||||
};
|
||||
moveCtrl.SetInputs(ref restoredInputs);
|
||||
moveCtrl.MoveInputVector = snapshot.MoveInputVector;
|
||||
moveCtrl.LookInputVector = snapshot.LookInputVector;
|
||||
moveCtrl.InternalVelocityAdd = snapshot.InternalVelocityAdd;
|
||||
|
||||
// 2. Восстанавливаем капсулу KCC (bypassInterpolation = true сбрасывает внутренние буферы перемещения)
|
||||
motor.SetPositionAndRotation(snapshot.Position, snapshot.Rotation, bypassInterpolation: true);
|
||||
motor.BaseVelocity = snapshot.BaseVelocity;
|
||||
motor.ApplyState(snapshot.MotorState, bypassInterpolation: true);
|
||||
|
||||
// 3. Восстанавливаем здоровье (без вызова анимаций смерти)
|
||||
if (entity.EntityHealth != null)
|
||||
{
|
||||
entity.EntityHealth.SetHealthData(snapshot.CurrentHealth);
|
||||
}
|
||||
|
||||
// 4. Восстанавливаем точную позу и фазу перехода Animator
|
||||
snapshot.AnimatorSnapshot.RestoreTo(entity.animator);
|
||||
|
||||
// 5. Мгновенно синхронизируем коллайдеры костей в PhysX
|
||||
Physics.SyncTransforms();
|
||||
snapshot.BonePose.ApplyTo(cachedBones);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,8 +197,8 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
layerSnap.NextFullPathHash = nextInfo.fullPathHash;
|
||||
layerSnap.NextNormalizedTime = nextInfo.normalizedTime;
|
||||
layerSnap.NextStateLength = Mathf.Max(0.0001f, nextInfo.length);
|
||||
layerSnap.TotalTransitionDuration = totalTransSeconds;
|
||||
layerSnap.ElapsedTransitionTime = totalTransSeconds * transInfo.normalizedTime;
|
||||
layerSnap.TotalTransitionDuration = Mathf.Max(0.0001f, totalTransSeconds);
|
||||
layerSnap.ElapsedTransitionTime = layerSnap.TotalTransitionDuration * transInfo.normalizedTime;
|
||||
}
|
||||
|
||||
_layers[i] = layerSnap;
|
||||
@@ -182,7 +224,7 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
}
|
||||
}
|
||||
|
||||
public void RestoreTo(Animator targetAnimator)
|
||||
public readonly void RestoreTo(Animator targetAnimator)
|
||||
{
|
||||
if (targetAnimator == null || _layers == null) return;
|
||||
|
||||
@@ -217,29 +259,25 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
|
||||
if (!layer.IsInTransition || layer.NextFullPathHash == 0)
|
||||
{
|
||||
// CrossFadeInFixedTime с длительностью 0f гарантированно убивает любой старый переход без Rebind()!
|
||||
float timeInSeconds = layer.NormalizedTime * layer.StateLength;
|
||||
float timeInSeconds = Mathf.Max(0f, layer.NormalizedTime * layer.StateLength);
|
||||
targetAnimator.CrossFadeInFixedTime(layer.FullPathHash, 0f, i, timeInSeconds);
|
||||
targetAnimator.Update(0f);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 1. Отматываем оба стейта к моменту начала перехода (минус ElapsedTransitionTime)
|
||||
float startSecondsA = (layer.NormalizedTime * layer.StateLength) - layer.ElapsedTransitionTime;
|
||||
float startSecondsB = (layer.NextNormalizedTime * layer.NextStateLength) - layer.ElapsedTransitionTime;
|
||||
// Защита от отрицательного времени (фикс бага старого AnimatorSnapshot)
|
||||
float startSecondsA = Mathf.Max(0f, (layer.NormalizedTime * layer.StateLength) - layer.ElapsedTransitionTime);
|
||||
float startSecondsB = Mathf.Max(0f, (layer.NextNormalizedTime * layer.NextStateLength) - layer.ElapsedTransitionTime);
|
||||
|
||||
targetAnimator.CrossFadeInFixedTime(layer.FullPathHash, 0f, i, startSecondsA);
|
||||
targetAnimator.Update(0f);
|
||||
|
||||
// 2. Запускаем переход с оригинальной полной длительностью
|
||||
targetAnimator.CrossFadeInFixedTime(
|
||||
layer.NextFullPathHash,
|
||||
layer.TotalTransitionDuration,
|
||||
i,
|
||||
startSecondsB);
|
||||
|
||||
// 3. Прокручиваем аниматор ровно на ElapsedTransitionTime вперед (с выключенным RootMotion),
|
||||
// чтобы внутренний вес смешивания Mecanim встал ровно в ту же долю процента!
|
||||
targetAnimator.Update(layer.ElapsedTransitionTime);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user