[置頂] Cg入門23: Fragment shader – UV動畫(序列幀)


讓動畫從1-9循環播放此紋理



源代碼:
Shader "Sbin/FragmentAnim"{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"

sampler2D _MainTex;
float4 _MainTex_ST;//紋理縮放偏移向量(Unity默認此變量賦值,變量名規則:紋理名_ST)

struct v2f{
float4 pos:POSITION;
float2 uv:TEXCOORD0;
};

v2f vert (appdata_full v)
{
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
o.uv = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;
return o;
}

fixed4 frag (v2f v) : COLOR
{
fixed4 col = tex2D(_MainTex, v.uv);//第一個參數:紋理,第二個參數UV向量
return col;
}
ENDCG
}
}
}

using UnityEngine;using System.Collections;public class FragmentAnim : MonoBehaviour{    public int rowCount;    //行數    public int columCount;  //列數    public int fps;         //播放速度    private int currentIndex;//當前播放索引值    IEnumerator Start()    {        Material mat = GetComponent<Renderer>().material;        float itemWidth = 1.0f / rowCount;      //每一幀寬度        float itemHeight = 1.0f / columCount;   //每一幀高度        while (true)        {            float offset_x = currentIndex % columCount * itemWidth;            float offset_y = currentIndex / rowCount * itemHeight;            mat.SetTextureScale("_MainTex", new Vector2(itemWidth, itemHeight));            mat.SetTextureOffset("_MainTex", new Vector2(offset_x, offset_y));            yield return new WaitForSeconds(1 / fps);            currentIndex = (++currentIndex) % (rowCount * columCount);        }    }}




注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com