最近在实现 FlappyBird 的实现,需要用到背景滚动,就上网搜集了很多方法,比较常用的就是利用 Shader 实现图片滚动,在这里记录一下。

下面的着色器代码实现了“滚动的背景”功能。这里定义了3个变量,其中 _MainTex 代表背景贴图,_Width 代表显示背景的百分比,_Distance 代表当前滚动的距离。核心代码为 “i.uv.x = frac(i.uv.x*_Width + _Distance);”,其中 frac 是取小数的函数,如 1.23 取出来是 0.23,其功能是将 i.uv.x 控制在 0 到 1 的范围,进而显示出来。

Shader "Custom/ImageRoll"
{
	Properties
	{
		_MainTex ("Main Tex", 2D) = "white" {}
		_Width ("Width", float) = 0.5
		_Distance ("Distance", float) = 0
	}
	SubShader
	{
		Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
		Pass
		{
			Tags { "LightMode"="ForwardBase" }
			ZTest off
			ZWrite Off
			Blend SrcAlpha OneMinusSrcAlpha
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			#include "UnityCG.cginc"
			sampler2D _MainTex;
			float _Width;
			float _Distance;
			struct a2v
			{
				float4 vertex : POSITION;
				float2 texcoord : TEXCOORD0;
			};
			struct v2f
			{
				float4 pos : SV_POSITION;
				float2 uv : TEXCOORD0;
			};
			v2f vert (a2v v)
			{
				v2f o;
				o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
				o.uv.x = v.texcoord.x;
				o.uv.y = v.texcoord.y;
				return o;
			}
			fixed4 frag (v2f i) : SV_Target
			{
				i.uv.x = frac(i.uv.x*_Width + _Distance);
				fixed4 c = tex2D(_MainTex, i.uv);
				return c;
			}
			ENDCG
		}
	}
	FallBack "Transparent/VertexLit"
}