在Unity中,对与Material的Tilling和offset属性,其中,Tilling指的是x或者y方向的缩放系数,其大小等于1/总帧数,offset为动画的每一帧的偏移量,其基础大小也是1/总帧数,但是每一帧的偏移量为一个变化的数,从0开始计算,第一帧为0*offset,第二帧为1*offset...依次类推。
如上图中共有7个单帧图片,从左至右。
Tilling:1/7=0.143
offset的基数为:0.143
在程序代码中设置,tilling为0.143,每一帧offset的便宜为0.143的整数倍,0,1,2,3,4,5,6(因为最多只有7帧)。
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class explosionControlls : MonoBehaviour {
public int _frameNum = 7;
public int _index = 0;
private float _frameRate = 0;
private float _myTime = 0;
private int _myIndex = 0;
// Use this for initialization
void Start () {
_frameRate = 1.0f / _frameNum; //计算每一帧的偏移量
Debug.Log("FrameRate=" + _frameRate);
}
// Update is called once per frame
void Update () {
_myTime += Time.deltaTime; //累加游戏运行的时间
_myIndex = (int)(_myTime * _frameNum); //计算动画的当前索引强制转换为整数
_index = _myIndex % _frameNum;
float offset = _index * _frameRate;
//Debug.Log(_myIndex);
//设置tiling和Offset
transform.GetComponent<Renderer>().material.SetTextureScale("_MainTex", new Vector2(_frameRate, 1));
//transform.GetComponent<Renderer>().material.mainTextureScale = new Vector2(_frameRate,1);
//transform.GetComponent<Renderer>().material.mainTextureOffset = new Vector2(offset, 0);
transform.GetComponent<Renderer>().material.SetTextureOffset("_MainTex", new Vector2(offset, 0));
if (_index==_frameNum-1)
{
Destroy(gameObject);
}
Debug.Log("FrameRate1=" + _frameRate);
}
}