播放序列帧脚本

/*--------------------------------------------------------------------

  • 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

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值