Unity3D之Foam浪花效果

shader需要设置在水上面,注意此shader不支持手机

Shader "Mobile/Unlit/Water Foam" {
	Properties {
		_Color("Color", Color) = (1,1,1,1) //此颜色的alpha值作为foam的透明度
		_MainTex ("Main Tex", 2D) = "gray" {}
		[NoScaleOffset] _FoamGradient ("Foam gradient ", 2D) = "white" {}
		_FoamStrength ("Foam strength", Range (0, 2)) = 0.2
		_FoamSpeed ("Foam Speed", Range (0, 1)) = 0.2
		_ScrollX ("Base layer Scroll speed X", Float) = 1.0
		_ScrollY ("Base layer Scroll speed Y", Float) = 0.0
		_Scroll2X ("2nd layer Scroll speed X", Float) = 1.0
		_Scroll2Y ("2nd layer Scroll speed Y", Float) = 0.0
		_Scroll2Scale("Scroll2 UV Scale", float) = 1 //第二层滚动的uv缩放
	}

	Subshader {
		Tags { "RenderType"="Opaque"}
		
		Pass {
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			#pragma multi_compile_fog

			#include "UnityCG.cginc"

			fixed _FoamStrength;
			fixed _FoamSpeed;
			sampler2D _CameraDepthTexture; //Depth Texture
			fixed4 _Color;


			sampler2D _MainTex;
			float4 _MainTex_ST;
			
			sampler2D _FoamGradient;
			
			half _ScrollX;
			half _ScrollY;
			half _Scroll2X;
			half _Scroll2Y;
			half _Scroll2Scale;
			

			struct appdata {
				float4 vertex : POSITION;
				float4 texcoord : TEXCOORD0;
				fixed4 color:COLOR;
			};

			struct v2f {
				float4 pos : SV_POSITION;
				half4 mainuv:TEXCOORD0;
				half4 scrolluv:TEXCOORD1;
				fixed4 color:COLOR;
				UNITY_FOG_COORDS(4)
			};

			v2f vert(appdata v)
			{
				v2f o;
				o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
				
				o.mainuv = ComputeScreenPos(o.pos) ;
				
				o.scrolluv.xy = TRANSFORM_TEX(v.texcoord,_MainTex) + frac(float2(_ScrollX, _ScrollY) * _Time.y);//frac取小数.
				o.scrolluv.zw = v.texcoord.xy *_Scroll2Scale + frac(float2(_Scroll2X, _Scroll2Y) * _Time.y);
				
				o.color = v.color;
				
				UNITY_TRANSFER_FOG(o,o.pos);
				return o;
			}

			half4 frag( v2f i ) : SV_Target
			{
				half4 color = tex2D(_MainTex,i.scrolluv.xy)* tex2D(_MainTex,i.scrolluv.zw)*_Color*2*i.color;

				float sceneZ = LinearEyeDepth (tex2Dproj(_CameraDepthTexture, UNITY_PROJ_COORD(i.mainuv)).r);
				float objectZ = i.mainuv.z;
				float intensityFactor = 1 - saturate((sceneZ - objectZ) / _FoamStrength);//saturate限制在0-1之间.
				half3 foamGradient = 1 - tex2D(_FoamGradient, float2(intensityFactor - _Time.y*_FoamSpeed, 0));
				color.rgb += foamGradient * intensityFactor*_Color.a ;
				
				UNITY_APPLY_FOG(i.fogCoord, color);
				return color;
			}
			ENDCG
		}
	}
}



除了设置上面的shader,还需要将Camera的深度模式设置为depth

GetComponent ().depthTextureMode = DepthTextureMode.Depth;


你可能感兴趣的:(Unity)