74 lines
2.3 KiB
C#
74 lines
2.3 KiB
C#
using UnityEngine;
|
|
|
|
namespace AibisDream.Kit
|
|
{
|
|
public class SpriteLooper : MonoBehaviour
|
|
{
|
|
private SpriteRenderer _fadeOutRenderer;
|
|
private SpriteRenderer _fadeInRenderer;
|
|
|
|
public Sprite[] sprites;
|
|
[Range(0, 1)]public float fadeRadio;
|
|
|
|
public float CurProgress { get; private set; }
|
|
|
|
private void Awake()
|
|
{
|
|
InitRefs();
|
|
}
|
|
|
|
private void InitRefs()
|
|
{
|
|
_fadeOutRenderer = transform.Find("Sprite1").GetComponent<SpriteRenderer>();
|
|
_fadeInRenderer = transform.Find("Sprite2").GetComponent<SpriteRenderer>();
|
|
}
|
|
|
|
public void Init()
|
|
{
|
|
CurProgress = 0;
|
|
// 激活初始状态
|
|
_fadeOutRenderer.sprite = sprites[0];
|
|
_fadeOutRenderer.color = Color.white;
|
|
_fadeInRenderer.sprite = sprites[1];
|
|
_fadeInRenderer.color = Color.clear;
|
|
}
|
|
|
|
public void SetLoopProgress(float progress)
|
|
{
|
|
CurProgress = progress;
|
|
|
|
// 将进度条转为图片序号和淡出进度
|
|
var calculator = new LoopDataCalculator(progress, sprites.Length, fadeRadio);
|
|
|
|
_fadeOutRenderer.sprite = sprites[calculator.CurIdx];
|
|
_fadeOutRenderer.color = calculator.FadeOutColor;
|
|
_fadeInRenderer.sprite = sprites[calculator.NextIdx];
|
|
_fadeInRenderer.color = calculator.FadeInColor;
|
|
}
|
|
}
|
|
|
|
public readonly struct LoopDataCalculator
|
|
{
|
|
private readonly float _progress;
|
|
private readonly float _localProgress;
|
|
private readonly float _fadeRadio;
|
|
public int CurIdx { get; }
|
|
public int NextIdx { get; }
|
|
|
|
public LoopDataCalculator(float progress, int spriteCount, float fadeRadio)
|
|
{
|
|
_progress = progress;
|
|
_localProgress = 1 / (float)spriteCount;
|
|
_fadeRadio = fadeRadio;
|
|
CurIdx = Mathf.FloorToInt(progress / _localProgress);
|
|
NextIdx = CurIdx + 1 >= spriteCount ? 0 : CurIdx + 1;
|
|
}
|
|
|
|
private float LeftProgress =>
|
|
Mathf.Clamp01((_progress - (CurIdx + 1 - _fadeRadio) * _localProgress) / (_localProgress * _fadeRadio));
|
|
|
|
public Color FadeOutColor => new(1f, 1f, 1f, 1 - LeftProgress);
|
|
|
|
public Color FadeInColor => new(1f, 1f, 1f, LeftProgress);
|
|
}
|
|
} |