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

22222.png

33333.png

Shader代码

Shader "Custom/SpriteSheet" {
	Properties{
		_MainTex("Base (RGB)", 2D) = "white" {}
		_HorizontalAmount("Horizontal Amount", float) = 0.0
		_VerticalAmount("Vertical Amount", float) = 0.0
		_Speed("Speed", Range(0.01, 32)) = 12
		_TransVal("Transparency Value", Range(0, 1)) = 1
	}
	SubShader{
		Tags {"Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent"}
		LOD 400
		Blend SrcAlpha OneMinusSrcAlpha

		CGPROGRAM
		#pragma surface surf Lambert alpha

		sampler2D _MainTex;
		float _HorizontalAmount;
		float _VerticalAmount;
		float _Speed;
		float _TransVal;

		struct Input {
			float2 uv_MainTex;
		};

		void surf(Input IN, inout SurfaceOutput o) {
			float2 spriteUV = IN.uv_MainTex;

			//fmod(x,y) : 取模,如果y为0结果不可预料。
			//floor(x)  : 向下取整
			//_Time.y   : 自场景加载开始所经过的时间 (单位:秒)

			float time = floor(_Time.y * _Speed);
			//行
			float row = floor(time / _HorizontalAmount);
			//列
			float column = floor(fmod(time, _HorizontalAmount));

			//定位到当前要显示的帧
			spriteUV.x += column;
			spriteUV.y -= row;

			//将UV的取值范围缩小到每一帧上
			spriteUV.x /= _HorizontalAmount;
			spriteUV.y /= _VerticalAmount;

			half4 c = tex2D(_MainTex, spriteUV);
			//漫反射颜色
			o.Albedo = c.rgb;
			//自发光颜色
			o.Emission = c.rgb;
			//用灰度值做为alpha
			o.Alpha = (c.r * 0.299 + c.g * 0.587 + c.b * 0.114) * _TransVal;
		}
		ENDCG
	}
	FallBack "Diffuse"
}

运行效果

11111.gif

标签: Shader

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号