Unity Shader 学习笔记(九) UV动画Shader实例

Unity Shader 学习笔记(九) UV动画Shader实例


Shader "Custom/UVAnimation" {
	Properties 
      {
		  //要播放的UV动画Texture
          _SpriteTex ("SpriteTexture (RGB)", 2D) = "white" {}
		  //UV动画的行数
          _SpriteRowCount ("RowCounts",float) = 0
		  //UV动画的列数
          _SpriteColumnCount ("ColumnCounts",float) = 0
		  //播放速度
          _Speed ("AnimationSpeed",Range(0.01,10)) = 4
      }
    SubShader 
     {
         Pass
         {
			//不透明物体
             Tags { "RenderType"="Opaque" }
             

			 //CG开始
             CGPROGRAM
             #pragma vertex vert
             #pragma fragment frag


             #include "UnityCG.cginc"
             //引用变量值
             uniform sampler2D _SpriteTex;
             uniform float _SpriteRowCount;
             uniform float _SpriteColumnCount;
             uniform float _Speed;
             
			 //顶点输出结构体
             struct VertexOutput
             {
                 float4 pos:SV_POSITION;
                 float2 uv:TEXCOORD0;
             };
 
			//appdate_base Unity预定义的输入结构体 包括了很多信息,可以直接用作为顶点着色程序的输入
             VertexOutput vert(appdata_base input)
             {
                 VertexOutput v_output;
                 v_output.pos = mul(UNITY_MATRIX_MVP,input.vertex);
                 v_output.uv = input.texcoord.xy;
                 return v_output;
             }
             
             float4 frag(VertexOutput input):COLOR
             {
				//根据行数和列数 算出有多少个精灵
                 float totalSpriteCount = _SpriteRowCount * _SpriteColumnCount;
				  // UV坐标值范围为0-1,获取单元格宽度
                 float rowAvgPercent = 1 / _SpriteColumnCount;
                 float columnAvgPercent = 1 / _SpriteRowCount;  
				 
				 //求余数  获取当前精灵索引
                 float SpriteIndex = fmod(_Time.y * _Speed,totalSpriteCount);    
				 //向下取整    
                 SpriteIndex = floor(SpriteIndex);   
				    
				 //获取当前行索引
                 float columnIndex = fmod(SpriteIndex,_SpriteColumnCount);
				 //获取当前列索引
                 float rowIndex = SpriteIndex / _SpriteColumnCount;
                 rowIndex = _SpriteRowCount - 1 - floor(rowIndex);

				 //计算当前索引所在的精灵的UV坐标
                 float2 spriteUV = input.uv;
                 spriteUV.x = (spriteUV.x + columnIndex) * rowAvgPercent;
                 spriteUV.y = (spriteUV.y + rowIndex) * columnAvgPercent;      
				 
				 //获取二维文理坐标color 显示到屏幕      
                 float4 col = tex2D(_SpriteTex,spriteUV);
                 return col;
             }

             //CG结束
             ENDCG
         }
     } 
     FallBack "Diffuse"

}


你可能感兴趣的:(Unity Shader 学习笔记(九) UV动画Shader实例)