/*--------------------------------------------------------------------
- Author Name: DXL
- Creation Time: 2018.10.10
- File Describe: UGUI序列帧动画播放
- ------------------------------------------------------------------*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Imageframe : MonoBehaviour
{
#region 序列帧动画实现
Image ImageSource;
int mCurFrame = 0; //当前正在播放的是哪一帧
float mDelta = 0;
public float FPS = 5; //播放速率
public List<Sprite> SpriteFrames; //存放序列帧图片
public bool IsPlaying = false; //当前是否正在播放动画
public bool Foward = true; //正向播放 还是 反向播放
public bool AutoPlay = false; //是否自动播放
public bool Loop = false; //是否循环播放
public bool OriginalSize = false; //是否使用图片资源的原始大小
//序列帧图片数量
public int FrameCount
{
get
{
return SpriteFrames.Count;
}
}
private void Awake()
{
ImageSource = GetComponent<Image>();
}
void Start()
{
if (AutoPlay)
{
if (Foward)
{
Play();
}
else
{
PlayReverse();
}
}
}
void Update()
{
if (!IsPlaying || FrameCount == 0)
{
return;
}
mDelta += Time.deltaTime;
if (mDelta > 1 / FPS) // 如果当前等待时间已经达到播放间隔,就可以播放一帧动画了
{
mDelta = 0;
if (Foward)
{
mCurFrame++;
}
else
{
mCurFrame--;
}
if (mCurFrame >= FrameCount) //正播
{
if (Loop)
{
mCurFrame = 0;
}
else
{
IsPlaying = false;
return;
}
}
else if (mCurFrame < 0) //倒播
{
if (Loop)
{
mCurFrame = FrameCount - 1;
}
else
{
IsPlaying = false;
return;
}
}
SetSprite(mCurFrame);
}
}
//正向播放序列帧动画
void Play()
{
IsPlaying = true;
Foward = true;
}
//反向播放序列帧动画
void PlayReverse()
{
IsPlaying = true;
Foward = false;
}
void SetSprite(int idx)
{
ImageSource.sprite = SpriteFrames[idx];
if (OriginalSize)
{
//显示原始图片大小
ImageSource.SetNativeSize();
}
}
#endregion
#region 对外控制接口,未检测,使用时请注意检查功能是否好使
//暂停
public void Pause()
{
IsPlaying = false;
}
//恢复
public void Resume()
{
IsPlaying = true;
}
//停止
public void Stop()
{
mCurFrame = 0;
SetSprite(mCurFrame);
IsPlaying = false;
}
//倒播
public void Rewind()
{
mCurFrame = 0;
SetSprite(mCurFrame);
Play();
}
#endregion
}