3D游戏中经常会用到往前走场景的淡入效果,实际就是物体从透明逐渐变实的过程
用Shader实现非常简单
实现思路:
1 设置淡入的起始距离 和 结束距离
2 在vertex阶段计算物体顶点与相机的距离
3 根据距离计算alpha
Shader如下
Shader"Custom/Fade"{
Properties{
_MainTex("Texture",2D)="white"{}
_FadeDistanceNear("Nearfadeoutdist(ViewSpace)",float)=35
_FadeDistanceFar("Farfadeoutdist(ViewSpace)",float)=40
}
SubShader
{
Tags{"Queue"="Transparent""RenderType"="Transparent"}
ZWriteOn
BlendSrcAlphaOneMinusSrcAlpha
pass
{
CGPROGRAM
#pragmavertexvert
#pragmafragmentfrag
#include"UnityCG.cginc"
sampler2D_MainTex;
float4_MainTex_ST;
structv2f{
float4pos:SV_POSITION;
float2uv:TEXCOORD0;
floatfade:TEXCOORD1;
};
float_FadeDistanceNear;
float_FadeDistanceFar;
v2fvert(appdata_basev)
{
v2fo;
o.pos=mul(UNITY_MATRIX_MVP,v.vertex);
o.uv=TRANSFORM_TEX(v.texcoord,_MainTex);
//相机坐标系的物体坐标
float3posView=mul(UNITY_MATRIX_MV,v.vertex).xyz;
//计算与相机距离
floatdis=length(posView);
//计算fade
o.fade=1-saturate((dis-_FadeDistanceNear)/(_FadeDistanceFar-_FadeDistanceNear));
returno;
}
float4frag(v2fi):COLOR
{
float4texCol=tex2D(_MainTex,i.uv);
float4outp=texCol;
//fade作为alpha
returnfloat4(outp.rgb,i.fade);
}
ENDCG
}
}
}
网友评论