unity-序列帧动画

时间:2022-07-07 03:37:44

  序列帧动画作为一种2D游戏中经常采用的动画技术,使用unity也是很好实现的。只要在场景中新建一个Quad,然后在添加上如下脚本即可:

using UnityEngine;
using System.Collections;

public class AnimateTest : MonoBehaviour {

private int startIndex = 266;
private int lastIndex = 331;
private string path = "dance/dance_";
private int currentIndex;
Texture frameAniTex;
public float framesPerSecond;

// Use this for initialization
void Start ()
{
currentIndex = startIndex;
}

void Update()
{
AnimaAlways();
}

// Update is called once per frame
void AnimaAlways()
{
int nowIndex = (int)(Time.time * framesPerSecond) % (lastIndex - startIndex+1);
if (currentIndex != startIndex + nowIndex)
{
currentIndex = startIndex + nowIndex;
frameAniTex = (Texture)Resources.Load(path + currentIndex.ToString("D5"));
if (frameAniTex == null)
{
Debug.Log("error:currentIndex:" + currentIndex);
}
GetComponent<Renderer>().material.mainTexture = frameAniTex;

}
}


}


注意:需要在quad上添加一个材质,后将材质的shader设置为standard,且设置rendering mode为cutout,这样主要是为了实现背景的透明,大致样子如下图,

unity-序列帧动画demo下载地址如下:

http://download.csdn.net/detail/xunni_5241/9620979

还有就是序列帧动画比较占用内存,在实际项目使用过程中,主要找到合适的实际进行内存资源的释放,还有就是unity经过自己的图片处理后会将图片大小放大很多,我们最终采用压缩型的assetbundle来进行资源的载入,在播放完成一个动画后将资源进行释放来缓解内存,要不在移动平台(安卓、ios)就会出现内存报警崩溃的问题。

本人文章纯属个人总结,且某些demo在项目采用前可能来自互联网,最终实验验证后实际项目中采用,若发现来自贵方,谅解;若发现,纰漏错误妄指正。