Files

98 lines
2.8 KiB
C#

using System;
using UnityEngine;
namespace AibisDream.Kit
{
public class Lerp : IAction
{
private static readonly SimpleObjectPool<Lerp> Pool = new(() => new Lerp(), null, 10);
private float _target;
private float _source;
private float _duration;
private Action<float> _onLerp;
private Action _onLerpFinish;
private float _currentTime;
public static Lerp Allocate(float source, float target, float duration, Action<float> onLerp = null,
Action onLerpFinish = null)
{
var retNode = Pool.Allocate();
retNode.ActionID = ActionKit.IDGenerator++;
retNode.IsFinalized = false;
retNode.Reset();
retNode._target = target;
retNode._source = source;
retNode._duration = duration;
retNode._onLerp = onLerp;
retNode._onLerpFinish = onLerpFinish;
return retNode;
}
public bool Paused { get; set; }
public void Reset()
{
Status = ActionStatus.NotStart;
Paused = false;
_currentTime = 0.0f;
}
public void Deinit()
{
if (!IsFinalized)
{
IsFinalized = true;
_onLerp = null;
_onLerpFinish = null;
ActionKitMonoBehaviourEvents.AddCallback(new ActionQueueRecycleCallback<Lerp>(Pool, this));
}
}
public ulong ActionID { get; set; }
public ActionStatus Status { get; set; }
public void OnStart()
{
_currentTime = 0.0f;
_onLerp?.Invoke(Mathf.Lerp(_source, _target, 0));
}
public void OnExecute(float dt)
{
_currentTime += dt;
if (_currentTime < _duration)
{
_onLerp?.Invoke(Mathf.Lerp(_source, _target, _currentTime / _duration));
}
else
{
this.Finish();
}
}
public void OnFinish()
{
_onLerp?.Invoke(Mathf.Lerp(_source, _target, 1.0f));
_onLerpFinish?.Invoke();
}
public bool IsFinalized { get; set; }
}
public static class LerpExtension
{
public static ISequence Lerp(this ISequence self, float a, float b, float duration, Action<float> onLerp = null,
Action onLerpFinish = null)
{
return self.Append(Kit.Lerp.Allocate(a, b, duration, onLerp, onLerpFinish));
}
public static ISequence Lerp01(this ISequence self, float duration, Action<float> onLerp = null,
Action onLerpFinish = null)
{
return self.Append(Kit.Lerp.Allocate(0, 1, duration, onLerp, onLerpFinish));
}
}
}