Shader——精灵表单动画

作者:追风剑情 发布于:2015-9-6 20:56 分类:Shader

一、准备一张精灵表单图片

flower.png

二、创建shader

Shader "Custom/SpriteSheet" {
	Properties {
		_MainTex ("Base (RGB)", 2D) = "white" {}
		_TexWidth ("Sheet Width", float) = 0.0
		_CellAmount ("Cell Amount", float) = 0.0
		_Speed ("Speed", Range(0.01, 32)) = 12
	}
	SubShader {
		Tags { "RenderType"="Opaque" }
		LOD 200
		
		CGPROGRAM
		#pragma surface surf Lambert

		sampler2D _MainTex;
		float _TexWidth;
		float _CellAmount;
		float _Speed;

		struct Input {
			float2 uv_MainTex;
		};

		void surf (Input IN, inout SurfaceOutput o) {
			float2 spriteUV = IN.uv_MainTex;
			
			float cellPixelWidth = _TexWidth/_CellAmount;
			float cellUVPercentage = cellPixelWidth/_TexWidth;
			//fmod(x,y) : 取模,如果y为0结果不可预料。
			float timeVal = fmod(_Time.y * _Speed, _CellAmount);
			timeVal = ceil(timeVal);//向上取整
			
			float xValue = spriteUV.x;
			
			xValue += cellUVPercentage * timeVal * _CellAmount;
			xValue *= cellUVPercentage;
			
			spriteUV = float2(xValue, spriteUV.y);
			
			half4 c = tex2D (_MainTex, spriteUV);
			o.Albedo = c.rgb;
			o.Alpha = c.a;
		}
		ENDCG
	} 
	FallBack "Diffuse"
}

三、运行效果

s1.png


s2.png

四、优化建议

把时间计算放到C#中进行。

void FixedUpdate(){
    timeValue = Mathf.Ceil(Time.time%16);
    transform.renderer.material.SetFloat("_TimeValue", timeValue);
}

标签: Shader

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号