BITKit/Src/Unity/Scripts/Entity/Components/Animator/EntityAnimator.cs

71 lines
2.3 KiB
C#
Raw Normal View History

2023-06-05 19:57:17 +08:00
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
2023-11-06 01:17:23 +08:00
using BITKit.Animations;
2023-06-05 19:57:17 +08:00
namespace BITKit.Entities
{
2023-11-06 01:17:23 +08:00
public sealed class EntityAnimator : EntityBehavior
2023-06-05 19:57:17 +08:00
{
2023-11-06 01:17:23 +08:00
[SerializeField] private UnityAnimator[] animators;
2023-10-24 23:38:22 +08:00
[SerializeReference, SubclassSelector] private References[] animationKeyWords;
[SerializeReference, SubclassSelector] private References _rootVelocity;
[SerializeReference, SubclassSelector] private References[] boolParameters;
[SerializeReference, SubclassSelector] private References[] floatParameters;
private List<string> keyWords;
2023-06-05 19:57:17 +08:00
public override void OnAwake()
{
keyWords = animationKeyWords.Select(x => x.Get()).ToList();
}
public override void OnStart()
{
2023-11-06 01:17:23 +08:00
UnityEntity.AddListener<string>(Constant.Animation.Play, Play);
2023-06-05 19:57:17 +08:00
}
2023-08-23 01:59:26 +08:00
private void Play(string animationName)
2023-06-05 19:57:17 +08:00
{
2023-11-06 01:17:23 +08:00
if (enabled is false) return;
2023-08-23 01:59:26 +08:00
if (animationKeyWords.Length is 0 || keyWords.Contains(animationName))
2023-06-05 19:57:17 +08:00
{
animators.ForEach(x =>
{
2023-08-23 01:59:26 +08:00
if (!x.isActiveAndEnabled) return;
2023-11-06 01:17:23 +08:00
x.Play(animationName);
2023-06-05 19:57:17 +08:00
});
}
}
public override void OnFixedUpdate(float deltaTime)
{
foreach (var boolPar in boolParameters)
{
animators.ForEach(x =>
{
if (x.isActiveAndEnabled)
2023-11-06 01:17:23 +08:00
x.animator.SetBool(boolPar, UnityEntity.Get<bool>(boolPar));
2023-06-05 19:57:17 +08:00
});
}
foreach (var floatPar in floatParameters)
{
animators.ForEach(x =>
{
if (x.isActiveAndEnabled)
2023-11-06 01:17:23 +08:00
x.animator.SetFloat(floatPar, UnityEntity.Get<float>(floatPar));
2023-06-05 19:57:17 +08:00
});
}
}
2023-11-06 01:17:23 +08:00
2023-08-23 01:59:26 +08:00
private void OnAnimatorMove()
2023-06-05 19:57:17 +08:00
{
2023-11-06 01:17:23 +08:00
if (enabled is false) return;
if (_rootVelocity is not null && UnityEntity is not null)
UnityEntity.Set(_rootVelocity, animators[0].animator.velocity);
2023-06-05 19:57:17 +08:00
}
2023-11-06 01:17:23 +08:00
2023-08-23 01:59:26 +08:00
// ReSharper disable once UnusedMember.Local
private void AnimationEvent(string eventName)
2023-06-05 19:57:17 +08:00
{
2023-11-06 01:17:23 +08:00
UnityEntity.Invoke(Constant.Animation.OnEvent, eventName);
2023-06-05 19:57:17 +08:00
}
}
}