在Unity中,使用材质或者着色器是通过创建一个材质来实现的,新建一个材质,会要求选择使用哪个着色器,默认的是Diffuse着色器。确定了着色器后,在材质属性面板中就会出现该着色器需要用到的一些属性,一般是贴图及对应的属性。
材质中贴图均有tiling和offset两个属性,它们用来定义当前材质球所使用的贴图区域(
直接将贴图贴到平面上一般会出现X和Y坐标倒置的问题,这个时候可以将tiling取反或者旋转贴图所在平面进行调整)。
offset:指明使用贴图的起始位置,取值范围为0-1
tiling:指明从offset位置处的大小区域,区域的取值范围一般为(-1,1),超过的话部分会按比例生成新的区域拼接上原先的。
也就是说,tiling指明了使用的贴图为输入贴图的多少倍,超过1的会自动拼接,同时offset指明了使用的贴图在输入贴图处的起始位置,假如位置超过了1,就会对1取余。
以一张图片为例,下面分别为原图和直接贴到一个平面上的效果
平面贴图后出现了X和Y方向倒置问题
下面是使用各种不同tiling和offset下的效果
(
上图中对于不同宽度的tiling,贴在的平面上的宽度没有对应的调整,所以看起来会有点比例失真
)
可以通过更新材质的offset和tiling属性来制作动画
下图是16个表情格图标,可以每次只显示图标中的某一小块区域来形成动画,参见这里
将该贴图应用到一个平面上面,再在该平面上附加如下代码:
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
// Use this for initialization
public int colCount = 4;
public int rowCount = 4;
//vars for animation
public int rowNumber = 0; //Zero Indexed
public int colNumber = 0; //Zero Indexed
public int totalCells = 16;
public int fps = 10;
//Maybe this should be a private var
private Vector2 offset;
//Update
void Update () { SetSpriteAnimation(colCount,rowCount,rowNumber,colNumber,totalCells,fps); }
//SetSpriteAnimation
void SetSpriteAnimation(int colCount ,int rowCount ,int rowNumber ,int colNumber,int totalCells,int fps ){
// Calculate index
int index = (int)(Time.time * fps);
// Repeat when exhausting all cells
index = index % totalCells;
// Size of every cell
float sizeX = 1.0f / colCount;
float sizeY = 1.0f / rowCount;
Vector2 size = new Vector2(sizeX,sizeY);
// split into horizontal and vertical index
var uIndex = index % colCount;
var vIndex = index / colCount;
// build offset
// v coordinate is the bottom of the image in opengl so we need to invert.
float offsetX = (uIndex+colNumber) * size.x;
float offsetY = (1.0f - size.y) - (vIndex + rowNumber) * size.y;
Vector2 offset = new Vector2(offsetX,offsetY);
renderer.material.SetTextureScale ("_MainTex", size);
renderer.material.SetTextureOffset ("_MainTex", offset);
}
}
播放后即可得到动态显示每个子图标的动画