在UnityShader中discard和clip是用在fs中的剔除像素的操作,可以很方便快速的实现模型的切割消融等效果,但单纯的discard(clip)操作会是图一这样的效果,很丑陋。加了反面渲染(cull off)之后是图二的效果,也很丑陋。图三图四就不一样了,像个实心的模型,高大上。
代码如下:
Shader "Unlit/CullShader"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_CullTex("Texture", 2D) = "white" {}
Value("ClipValue",Range(-5,5))=0
}
CGINCLUDE
#include "UnityCG.cginc"
#include "Lighting.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
float3 normal:NORMAL;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float4 pos:TEXCOORD1;
float3 WorldNor:TEXCOORD2;
};
sampler2D _MainTex;
float4 _MainTex_ST;
sampler2D _CullTex;
float Value;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
o.WorldNor = normalize(UnityObjectToWorldNormal(v.normal));
o.pos= v.vertex;
return o;
}
fixed4 fragfront (v2f i) : SV_Target
{
if (i.pos.y > Value) {
discard;
}
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
float3 LightDir = normalize(_WorldSpaceLightPos0.xyz);
fixed4 col = tex2D(_MainTex, i.uv);
float3 diffuse=_LightColor0*col*max(0, dot(i.WorldNor,LightDir)*0.5+0.5);
fixed3 color = ambient + diffuse;
return fixed4(color,1);
}
fixed4 fragback(v2f i) : SV_Target
{
if (i.pos.y > Value) {
discard;
}
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
float3 LightDir = normalize(_WorldSpaceLightPos0.xyz);
float3 diffuse = _LightColor0*max(0, dot(fixed3(0,1,0),LightDir)*0.5+0.1);
fixed3 color = ambient + diffuse;
return fixed4(color,1);
}
ENDCG
SubShader
{
Tags{ "RenderType" = "Opaque" }
LOD 100
Pass
{
cull back//剔除背面,渲染正面
CGPROGRAM
#pragma vertex vert
#pragma fragment fragfront
ENDCG
}
Pass
{
cull front//剔除正面,渲染背面
CGPROGRAM
#pragma vertex vert
#pragma fragment fragback
ENDCG
}
}
}