【本系列文章系学习 唐福幸《Unity ShaderLab 新手宝典》的笔记,包含个人理解,如有错误欢迎批评指出
透明效果
7.3.5 混合透明效果
根据7.3.4:给之前的代码加入如下语句
SubShader
{
Tags
{
"Queue" = "Transparent"
"RenderType" = "Transparent"
"IgnoreProjector" = "True"
}
Pass
{
ZWrite Off
Blend SrcAlpha OneMinusSreAlpha
}
}
先拿最早的贴图shader 4.3.4.3来试试
Shader "Chapter7/TransImg1"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_MainColor ("MainColor",Color) = (1,1,1,1)
}
SubShader
{
//添加透明相关标签
Tags
{
"Queue" = "Transparent"
"RenderType" = "Transparent"
"IgnoreProjector" = "True"
}
Pass
{
ZWrite off//关闭深度写入
Blend SrcAlpha OneMinusSrcAlpha//普通的透明叠加
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
sampler2D _MainTex;
float4 _MainTex_ST;//表示uv的缩放和平移
float4 _MainColor;
void vert(in float4 vertex : POSITION, in float2 uv : TEXCOORD0, out float4 position : SV_POSITION, out float2 texcoord : TEXCOORD0)
{
position = UnityObjectToClipPos(vertex);
texcoord = uv * _MainTex_ST.xy + _MainTex_ST.zw;//纹理坐标的计算公式
}
void frag(in float4 position : SV_POSITION, in float2 texcoord : TEXCOORD0, out fixed4 color : SV_TARGET)
{
color = tex2D(_MainTex, texcoord) * _MainColor;//使用纹理坐标texcoord对纹理_MainTex进行采样,结果与_MainColor颜色混合
//tex2D:https://blog.csdn.net/yuanerjiang/article/details/88681589
}
ENDCG
}
}
}
这里调一下透明度
Shader "Chapter7/TransImg2"
{
Properties
{
_MainColor("Main Color",Color)=(1,1,1,1)
}
SubShader
{
Tags
{
"Queue" = "Transparent"
"RenderType" = "Transparent"
"IgnoreProjector" = "True"
}
Pass
{
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#include "UnityLightingCommon.cginc"
struct v2f
{
float4 pos : SV_POSITION;
fixed4 dif : COLOR0;
};
fixed4 _MainColor;
v2f vert(appdata_base v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
float3 n = UnityObjectToWorldNormal(v.normal);
fixed3 l = normalize(_WorldSpaceLightPos0.xyz);
fixed ndotl = dot(n,l);
o.dif = _LightColor0 * _MainColor * saturate(ndotl);
//o.dif = _LightColor0 * _MainColor * (0.5 * ndotl + 0.5);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
return i.dif;
}
ENDCG
}
}
}
Lambert因为背光面被saturate函数变成0了,所以透明效果渲染不出来
再试试Half-Lambert 6.3
只把上面这两句注释交换一下
//o.dif = _LightColor0 * _MainColor * saturate(ndotl);
o.dif = _LightColor0 * _MainColor * (0.5 * ndotl + 0.5);
这时候背面就可以看到了