Unity3D 将一张贴图转变成2D动画的公用脚本
using UnityEngine; using System.Collections; public class AnimationController : MonoBehaviour { float myTime = 0; bool isPlay = false; /// <summary> /// 2D动画播放 /// </summary> /// <param name="colSize">列数</param> /// <param name="rowSize">行数</param> /// <param name="colFrameStart">从第几列开始</param> /// <param name="rowFrameStart">从第几行开始</param> /// <param name="totalFrames">图片总共的帧数</param> /// <param name="framesPreSecond">一秒钟播放的帧数</param> /// <param name="totalTime">动画播放的时间 为0就一直播放</param> /// <returns></returns> public bool AnimationSprite(int colSize, int rowSize, int colFrameStart, int rowFrameStart, int totalFrames, int framesPreSecond, int totalTime) { myTime += Time.deltaTime; if (totalTime != 0 && myTime > totalTime) { isPlay = false; myTime = 0; return isPlay; } int index = (int)(Time.time * framesPreSecond%totalFrames); Vector2 size = new Vector2(1.0f / colSize, 1.0f / rowSize); float u = index % colSize; float v = index / colSize; Vector2 offset = new Vector2((u+colFrameStart)*size.x,(1.0f-size.y)-(v+rowFrameStart)*size.y); renderer.material.mainTextureScale = size; renderer.material.mainTextureOffset = offset; return true; } }
将上述的脚本拖拽至一个物体,然后新建一个脚本,代码如下:
private bool isPlay = true;//是否播放 void Update() { if (isPlay) { isPlay=animationHelper.AnimationSprite(3, 6, 0, 0, 18, 12, 3); } }
就可以实现动画的播放