功能如题,原理这里不做多余解释,直接上代码。
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Image))]
public class UI2dAnimation : MonoBehaviour
{
#region 字段
#region Private
private Image m_ImageSource = null;
private int m_CurFrame = 0;
private float m_Delta = 0;
#endregion
#region Public
public Sprite[] SpriteFrames;
public float FPS = 5;
public bool IsPlaying = false;
public bool Foward = true;
public bool AutoPlay = false;
public bool Loop = true;
#endregion
#endregion
public int FrameCount { get { return SpriteFrames.Length; } }
#region Unity系统函数
void Awake()
{
m_ImageSource = GetComponent<Image>();
}
void Start()
{
if (AutoPlay)
Play();
else
IsPlaying = false;
}
void Update()
{
if (!IsPlaying || 0 == FrameCount) return;
m_Delta += Time.deltaTime;
if (m_Delta > 1 / FPS)
{
m_Delta = 0;
if (Foward) m_CurFrame++;
else m_CurFrame--;
if (Loop)
{
if (m_CurFrame >= FrameCount)
{
m_CurFrame = 0;
}
else if (m_CurFrame < 0)
{
m_CurFrame = FrameCount - 1;
}
}
else
{
IsPlaying = false;
return;
}
SetSprite(m_CurFrame);
}
}
#endregion
private void SetSprite(int idx)
{
m_ImageSource.sprite = SpriteFrames[idx];
}
#region Public
public void Play()
{
IsPlaying = true;
Foward = true;
}
public void PlayReverse()
{
IsPlaying = true;
Foward = false;
}
public void Pause()
{
IsPlaying = false;
}
public void Resume()
{
if (!IsPlaying)
{
IsPlaying = true;
}
}
public void Stop()
{
m_CurFrame = 0;
SetSprite(m_CurFrame);
IsPlaying = false;
}
public void Rewind()
{
m_CurFrame = 0;
SetSprite(m_CurFrame);
Play();
}
#endregion
}
|