253 lines
11 KiB
C#
253 lines
11 KiB
C#
using Code.OfficeGame.BattleMode.Health;
|
||
using UnityEngine;
|
||
|
||
namespace Code.OfficeGame.BattleMode.Actions
|
||
{
|
||
public struct EntitySnapshot
|
||
{
|
||
// 1. KCC Motor
|
||
public Vector3 Position;
|
||
public Quaternion Rotation;
|
||
public Vector3 BaseVelocity;
|
||
|
||
// 2. MovementController
|
||
public bool IsFrozen;
|
||
public Vector3 MoveInputVector;
|
||
public Vector3 LookInputVector;
|
||
|
||
// 3. Здоровье
|
||
public HealthData CurrentHealth;
|
||
|
||
// 4. Аниматор
|
||
public AnimatorSnapshot AnimatorSnapshot;
|
||
|
||
public static EntitySnapshot GetSnapshot(EntityProperties entity)
|
||
{
|
||
var motor = entity.KinematicCharacterMotor;
|
||
var moveCtrl = entity.MovementController;
|
||
|
||
return new EntitySnapshot
|
||
{
|
||
Position = motor.TransientPosition,
|
||
Rotation = motor.TransientRotation,
|
||
BaseVelocity = motor.BaseVelocity,
|
||
|
||
IsFrozen = moveCtrl.Freeze,
|
||
// Сохраните текущие входы контроллера (добавьте публичные геттеры в MovementController, если они приватные)
|
||
MoveInputVector = moveCtrl.MoveInputVector,
|
||
LookInputVector = moveCtrl.LookInputVector,
|
||
|
||
CurrentHealth = entity.EntityHealth != null ? entity.EntityHealth.HealthData.CurrentValue : default,
|
||
AnimatorSnapshot = AnimatorSnapshot.GetSnapshot(entity.animator)
|
||
};
|
||
}
|
||
|
||
public static void RestoreSnapshot(EntityProperties entity, 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);
|
||
|
||
// 2. Восстанавливаем капсулу KCC (bypassInterpolation = true сбрасывает внутренние буферы перемещения)
|
||
motor.SetPositionAndRotation(snapshot.Position, snapshot.Rotation, bypassInterpolation: true);
|
||
motor.BaseVelocity = snapshot.BaseVelocity;
|
||
|
||
// 3. Восстанавливаем здоровье (без вызова анимаций смерти)
|
||
if (entity.EntityHealth != null)
|
||
{
|
||
entity.EntityHealth.SetHealthData(snapshot.CurrentHealth);
|
||
}
|
||
|
||
// 4. Восстанавливаем точную позу и фазу перехода Animator
|
||
snapshot.AnimatorSnapshot.RestoreTo(entity.animator);
|
||
|
||
// 5. Мгновенно синхронизируем коллайдеры костей в PhysX
|
||
Physics.SyncTransforms();
|
||
}
|
||
}
|
||
|
||
public struct AnimatorSnapshot
|
||
{
|
||
public struct LayerStateSnapshot
|
||
{
|
||
public int FullPathHash;
|
||
public float NormalizedTime;
|
||
public float StateLength;
|
||
public float LayerWeight;
|
||
|
||
public bool IsInTransition;
|
||
public int NextFullPathHash;
|
||
public float NextNormalizedTime;
|
||
public float NextStateLength;
|
||
public float TotalTransitionDuration;
|
||
public float ElapsedTransitionTime;
|
||
}
|
||
|
||
public struct ParameterSnapshot
|
||
{
|
||
public int NameHash;
|
||
public AnimatorControllerParameterType Type;
|
||
public float FloatValue;
|
||
public int IntValue;
|
||
public bool BoolValue;
|
||
}
|
||
|
||
private LayerStateSnapshot[] _layers;
|
||
private ParameterSnapshot[] _parameters;
|
||
private Vector3 _localPosition;
|
||
private Quaternion _localRotation;
|
||
private float _speed;
|
||
private bool _applyRootMotion;
|
||
|
||
public static AnimatorSnapshot GetSnapshot(Animator animator)
|
||
{
|
||
var snapshot = new AnimatorSnapshot();
|
||
snapshot.CaptureFrom(animator);
|
||
return snapshot;
|
||
}
|
||
|
||
public void CaptureFrom(Animator animator)
|
||
{
|
||
if (animator == null) return;
|
||
|
||
Transform animTransform = animator.transform;
|
||
_localPosition = animTransform.localPosition;
|
||
_localRotation = animTransform.localRotation;
|
||
_speed = animator.speed;
|
||
_applyRootMotion = animator.applyRootMotion;
|
||
|
||
int layerCount = animator.layerCount;
|
||
_layers = new LayerStateSnapshot[layerCount];
|
||
|
||
for (int i = 0; i < layerCount; i++)
|
||
{
|
||
AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(i);
|
||
bool inTransition = animator.IsInTransition(i);
|
||
|
||
var layerSnap = new LayerStateSnapshot
|
||
{
|
||
FullPathHash = stateInfo.fullPathHash,
|
||
NormalizedTime = stateInfo.normalizedTime,
|
||
StateLength = Mathf.Max(0.0001f, stateInfo.length),
|
||
LayerWeight = animator.GetLayerWeight(i),
|
||
IsInTransition = inTransition
|
||
};
|
||
|
||
if (inTransition)
|
||
{
|
||
AnimatorStateInfo nextInfo = animator.GetNextAnimatorStateInfo(i);
|
||
AnimatorTransitionInfo transInfo = animator.GetAnimatorTransitionInfo(i);
|
||
|
||
float totalTransSeconds = transInfo.durationUnit == DurationUnit.Fixed
|
||
? transInfo.duration
|
||
: transInfo.duration * stateInfo.length;
|
||
|
||
layerSnap.NextFullPathHash = nextInfo.fullPathHash;
|
||
layerSnap.NextNormalizedTime = nextInfo.normalizedTime;
|
||
layerSnap.NextStateLength = Mathf.Max(0.0001f, nextInfo.length);
|
||
layerSnap.TotalTransitionDuration = totalTransSeconds;
|
||
layerSnap.ElapsedTransitionTime = totalTransSeconds * transInfo.normalizedTime;
|
||
}
|
||
|
||
_layers[i] = layerSnap;
|
||
}
|
||
|
||
int paramCount = animator.parameterCount;
|
||
_parameters = new ParameterSnapshot[paramCount];
|
||
|
||
for (int i = 0; i < paramCount; i++)
|
||
{
|
||
AnimatorControllerParameter param = animator.GetParameter(i);
|
||
int hash = param.nameHash;
|
||
var pSnap = new ParameterSnapshot { NameHash = hash, Type = param.type };
|
||
|
||
switch (param.type)
|
||
{
|
||
case AnimatorControllerParameterType.Float: pSnap.FloatValue = animator.GetFloat(hash); break;
|
||
case AnimatorControllerParameterType.Int: pSnap.IntValue = animator.GetInteger(hash); break;
|
||
case AnimatorControllerParameterType.Bool:
|
||
case AnimatorControllerParameterType.Trigger: pSnap.BoolValue = animator.GetBool(hash); break;
|
||
}
|
||
_parameters[i] = pSnap;
|
||
}
|
||
}
|
||
|
||
public void RestoreTo(Animator targetAnimator)
|
||
{
|
||
if (targetAnimator == null || _layers == null) return;
|
||
|
||
targetAnimator.applyRootMotion = false;
|
||
targetAnimator.speed = _speed;
|
||
|
||
if (_parameters != null)
|
||
{
|
||
for (int i = 0; i < _parameters.Length; i++)
|
||
{
|
||
var p = _parameters[i];
|
||
if (targetAnimator.IsParameterControlledByCurve(p.NameHash)) continue;
|
||
|
||
switch (p.Type)
|
||
{
|
||
case AnimatorControllerParameterType.Float: targetAnimator.SetFloat(p.NameHash, p.FloatValue); break;
|
||
case AnimatorControllerParameterType.Int: targetAnimator.SetInteger(p.NameHash, p.IntValue); break;
|
||
case AnimatorControllerParameterType.Bool: targetAnimator.SetBool(p.NameHash, p.BoolValue); break;
|
||
case AnimatorControllerParameterType.Trigger:
|
||
if (p.BoolValue) targetAnimator.SetTrigger(p.NameHash);
|
||
else targetAnimator.ResetTrigger(p.NameHash);
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
int layerCount = Mathf.Min(_layers.Length, targetAnimator.layerCount);
|
||
for (int i = 0; i < layerCount; i++)
|
||
{
|
||
var layer = _layers[i];
|
||
targetAnimator.SetLayerWeight(i, layer.LayerWeight);
|
||
|
||
if (!layer.IsInTransition || layer.NextFullPathHash == 0)
|
||
{
|
||
// CrossFadeInFixedTime с длительностью 0f гарантированно убивает любой старый переход без Rebind()!
|
||
float timeInSeconds = 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;
|
||
|
||
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);
|
||
}
|
||
}
|
||
|
||
Transform targetTransform = targetAnimator.transform;
|
||
targetTransform.localPosition = _localPosition;
|
||
targetTransform.localRotation = _localRotation;
|
||
targetAnimator.applyRootMotion = _applyRootMotion;
|
||
}
|
||
}
|
||
} |