unity_shader之实现场景淡入淡出

3D游戏中经常会用到往前走场景的淡入效果,实际就是物体从透明逐渐变实的过程
用Shader实现非常简单

实现思路:
1 设置淡入的起始距离 和 结束距离
2 在vertex阶段计算物体顶点与相机的距离
3 根据距离计算alpha

Shader如下
 

  1. Shader "Custom/Fade" {
  2.     Properties {
  3.         _MainTex ("Texture"2D) = "white" { }
  4.         _FadeDistanceNear ("Near fadeout dist (View Space)"float) = 35    
  5.         _FadeDistanceFar ("Far fadeout dist (View Space)"float) = 40
  6.     }
  7.     SubShader
  8.     {
  9.         Tags { "Queue"="Transparent" "RenderType"="Transparent"}
  10.         ZWrite On
  11.         Blend SrcAlpha OneMinusSrcAlpha
  12.         pass
  13.         {
  14.             CGPROGRAM
  15.             #pragma vertex vert
  16.             #pragma fragment frag
  17.             #include "UnityCG.cginc"
  18.             sampler2D _MainTex;
  19.             float4 _MainTex_ST;
  20.             struct v2f {
  21.                 float4  pos : SV_POSITION;
  22.                 float2  uv : TEXCOORD0;
  23.                 float fade:TEXCOORD1;
  24.             } ;
  25.             float _FadeDistanceNear;
  26.             float _FadeDistanceFar;
  27.             v2f vert (appdata_base v)
  28.             {
  29.                 v2f o;
  30.                 o.pos = mul(UNITY_MATRIX_MVP,v.vertex);
  31.                 o.uv = TRANSFORM_TEX(v.texcoord,_MainTex);
  32.                 //相机坐标系的物体坐标
  33.                 float3 posView = mul(UNITY_MATRIX_MV,v.vertex).xyz;
  34.                 //计算与相机距离
  35.                 float dis = length(posView);
  36.                 //计算fade
  37.                 o.fade = 1 - saturate((dis - _FadeDistanceNear)/(_FadeDistanceFar - _FadeDistanceNear));
  38.                 return o;
  39.             }
  40.             float4 frag (v2f i) : COLOR
  41.             {
  42.                 float4 texCol = tex2D(_MainTex,i.uv);
  43.                 float4 outp = texCol;
  44.                 //fade作为alpha
  45.                 return float4(outp.rgb,i.fade);
  46.             }
  47.             ENDCG
  48.         }
  49.     }
  50. }

 

转载自风宇冲新浪博客

你可能感兴趣的:(Unity)