quantum-space-buddies/QSB/Animation/AnimatorMirror.cs

98 lines
2.6 KiB
C#
Raw Normal View History

2020-11-04 20:01:28 +00:00
using OWML.Common;
2020-11-08 19:32:04 +00:00
using QSB.Player;
2020-11-04 20:01:28 +00:00
using QSB.Utility;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
2020-02-21 22:36:07 +00:00
namespace QSB.Animation
{
2020-12-02 21:23:01 +00:00
public class AnimatorMirror : MonoBehaviour
{
private const float SmoothTime = 0.05f;
2020-12-02 21:23:01 +00:00
private Animator _from;
private Animator _to;
2020-12-02 21:23:01 +00:00
private readonly Dictionary<string, AnimFloatParam> _floatParams = new Dictionary<string, AnimFloatParam>();
2020-12-02 21:23:01 +00:00
public void Init(Animator from, Animator to)
{
_from = from;
_to = to;
if (_from.runtimeAnimatorController == null)
{
DebugLog.DebugWrite($"Warning - \"From\" ({from.name}) controller is null.", MessageType.Warning);
_from.runtimeAnimatorController = _to.runtimeAnimatorController;
}
else if (_to.runtimeAnimatorController == null)
{
DebugLog.DebugWrite($"Warning - \"To\" ({to.name}) controller is null.", MessageType.Warning);
_to.runtimeAnimatorController = _from.runtimeAnimatorController;
}
foreach (var param in _from.parameters.Where(p => p.type == AnimatorControllerParameterType.Float))
{
_floatParams.Add(param.name, new AnimFloatParam());
}
}
2020-12-02 21:23:01 +00:00
private PlayerInfo GetPlayer()
{
return QSBPlayerManager.GetSyncObjects<AnimationSync>().First(x => x.Mirror == this).Player;
}
2020-11-08 19:32:04 +00:00
2020-12-02 21:23:01 +00:00
private void Update()
{
if (_to == null || _from == null)
{
return;
}
if (_to.runtimeAnimatorController != _from.runtimeAnimatorController)
{
_to.runtimeAnimatorController = _from.runtimeAnimatorController;
}
SyncParams();
SmoothFloats();
}
2020-12-02 21:23:01 +00:00
private void SyncParams()
{
foreach (var fromParam in _from.parameters)
{
switch (fromParam.type)
{
case AnimatorControllerParameterType.Float:
if (!_floatParams.ContainsKey(fromParam.name))
{
DebugLog.ToConsole($"Warning - Tried to sync anim float that doesn't exist in dict : {fromParam.name}", MessageType.Warning);
RebuildFloatParams();
break;
}
_floatParams[fromParam.name].Target = _from.GetFloat(fromParam.name);
break;
case AnimatorControllerParameterType.Bool:
_to.SetBool(fromParam.name, _from.GetBool(fromParam.name));
break;
}
}
}
2020-12-02 21:23:01 +00:00
private void SmoothFloats()
{
foreach (var floatParam in _floatParams)
{
var current = floatParam.Value.Smooth(SmoothTime);
_to.SetFloat(floatParam.Key, current);
}
}
2020-11-07 21:25:22 +00:00
2020-12-02 21:23:01 +00:00
public void RebuildFloatParams()
{
_floatParams.Clear();
foreach (var param in _from.parameters.Where(p => p.type == AnimatorControllerParameterType.Float))
{
_floatParams.Add(param.name, new AnimFloatParam());
}
}
}
2020-11-08 16:13:10 +00:00
}