参考地址:http://www.manew.com/thread-110080-1-1.html
总结:
获取顶点的世界坐标,根据世界坐标的y计算出雾化的比例,和最终颜色进行差值。
Shader "Custom/Fog_cg"
{
Properties
{
_Color("Color",Color)=(1,1,1,1)
_MainTex("Texture",2D) = "white"{}
_FogColor("Fog Color",Color) = (0.3,0.4,0.7,1.0)
_FogStart("Fog Start Y", float) = 0
_FogEnd("Fog End Y",float) = 0
}
SubShader
{
Tags { "RenderType"="Opaque" }
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
half fog :TEXCOORD1;
};
fixed4 _Color;
fixed4 _FogColor;
half _FogStart;
half _FogEnd;
sampler2D _MainTex;
float4 _MainTex_ST;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
float4 pos = mul(unity_ObjectToWorld, v.vertex).xyzw;
o.fog = saturate((_FogStart - pos.y) / (_FogStart - _FogEnd));
return o;
}
fixed4 frag(v2f i) : SV_Target
{
// sample the texture
fixed4 col = tex2D(_MainTex, i.uv);
fixed3 fogColor = _FogColor.rgb;
fixed3 tintColor = _Color.rgb;
col.rgb = lerp(col.rgb*tintColor, fogColor, i.fog);
return col;
}
ENDCG
}
}
}
效果: