Unity Shader - ZTest, ZWrite 实现遮自定义的挡绘制效果

Project

源项目:Project

Demo

Unity Shader - ZTest, ZWrite 实现遮自定义的挡绘制效果_第1张图片

Shader

实现代码很简单

/*
	author	:	jave.lin
	date	:	2018-11-06
*/
Shader "Custom/MaskTintTex"
{
	Properties
	{
		_MainTex ("Texture", 2D) = "white" {}
		_MaskTex ("Texture", 2D) = "white" {}
		_MaskTint ("MaskColor", Color) = (1,1,1,1)
	}
	SubShader
	{
		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;
			};

			sampler2D _MainTex;
			float4 _MainTex_ST;
			
			v2f vert (appdata v)
			{
				v2f o;
				o.vertex = UnityObjectToClipPos(v.vertex);
				o.uv = TRANSFORM_TEX(v.uv, _MainTex);
				return o;
			}
			
			fixed4 frag (v2f i) : SV_Target
			{
				fixed4 col = tex2D(_MainTex, i.uv);
				return col;
			}
			ENDCG
		}

		Pass
		{
			ZTest Greater
			ZWrite Off
			Blend SrcAlpha OneMinusSrcAlpha

			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag

			#include "UnityCG.cginc"

			struct appdata
			{
				float2 uv : TEXCOORD0;
				float4 vertex : POSITION;
			};

			struct v2f
			{
				float2 uv : TEXCOORD0;
				float4 vertex : SV_POSITION;
			};

			sampler2D _MaskTex;
			float4 _MaskTex_ST;
			fixed4 _MaskTint;
			
			v2f vert (appdata v)
			{
				v2f o;
				o.vertex = UnityObjectToClipPos(v.vertex);
				o.uv = TRANSFORM_TEX(v.uv, _MaskTex);
				return o;
			}
			
			fixed4 frag (v2f i) : SV_Target
			{
				fixed4 col = tex2D(_MaskTex, i.uv);
				return col * _MaskTint;
			}
			ENDCG
		}
	}
}

总结

该效果其实很多3D游戏中都会使用到
如:
某个角色被建筑物挡住,需要效果角色的外发光轮廓、或是X光一样的透视效果,等等,都可以调整第二个pass来达到效果

这里列出一个之前写的测试例子

        // Draw Mask
        Pass
		{
            Name "DrawMask"
			ZTest Greater
			ZWrite Off
			Blend One OneMinusSrcAlpha

			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag

			#include "UnityCG.cginc"

			struct appdata
			{
				float3 normal : NORMAL;
				float4 vertex : POSITION;
			};

			struct v2f
			{
				float4 vertex : SV_POSITION;
				float3 worldPos : TEXCOORD1;
				float3 worldNormal : TEXCOORD0;
			};

			float4 _MaskColor;
			fixed4 _MaskRimColor;
			
			v2f vert (appdata v)
			{
				v2f o = (v2f)0;
				o.vertex = UnityObjectToClipPos(v.vertex);
				o.worldNormal = UnityObjectToWorldNormal(v.normal);
				o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
				return o;
			}
			
			fixed4 frag (v2f i) : SV_Target
			{
				fixed3 viewDir = normalize(_WorldSpaceCameraPos.xyz - i.worldPos);
				float viewDotNormal = dot(viewDir, i.worldNormal);
				return _MaskColor * (1 - viewDotNormal) * _MaskRimColor;
			}
			ENDCG
		}

效果
Unity Shader - ZTest, ZWrite 实现遮自定义的挡绘制效果_第2张图片
这个边缘绘制不是很好,其实可以替换成:depth + dot(view, normal)来结合处理,会好很多

你可能感兴趣的:(unity,unity-shader)