1. 程式人生 > >unity中實現一個光照越強透明度越高的shader

unity中實現一個光照越強透明度越高的shader

可能描述的不清楚,先看下效果:


就是這樣,被燈光照亮的部分,會變透明,而且越亮透明度越高。

這裡主要就是通過計算當先位置的法線在燈光方向上的投影大小,投影越大則亮度越高,

因為透明度為0-1,所這裡我們把(1-亮度)作為透明度即可。

完整的shader程式碼:

Shader "Custom/NewSurfaceShader" {
	Properties{
        _MainTex ("Main Tex",2D) = "white" {}
    }

	SubShader {
        //開啟透明 這是光照模式
        Tags{"IgnoreProjector"="True" "LightMode" = "ForwardBase" "Queue"="Transparent" "RenderType"="Transparent"}

        Pass{
            ZWrite On
            ColorMask 0
        }
		Pass{
            ZWrite Off
            Blend SrcAlpha OneMinusSrcAlpha
            CGPROGRAM
            // Physically based Standard lighting model, and enable shadows on all light types
            #pragma vertex vert
            #pragma fragment frag

            #include "Lighting.cginc"

            sampler2D _MainTex;
            float4 _MainTex_ST;

            struct a2v{
                float4 vertex : POSITION;
                float3 normal : NORMAL;
                float4 texcoord : TEXCOORD0;
            };

            struct v2f {
                float4 pos : SV_POSITION;
                float3 worldNormal : TEXCOORD0;
                float3 worldPos : TEXCOORD1;
                float2 uv : TEXCOORD2;
            };

            v2f vert(a2v v) {
                v2f o;
                o.pos = UnityObjectToClipPos (v.vertex);
                o.worldNormal = UnityObjectToWorldNormal(v.normal);
                o.worldPos =  mul(unity_ObjectToWorld,v.vertex).xyz;
                o.uv = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;
                return o;

            }

            fixed4 frag(v2f i) : SV_Target{
                //獲取法線方向
                fixed3 worldNormal = normalize(i.worldNormal);
                //燈光方向
                fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));
                //使用環境光得到光照後的顏色
                fixed3 c = UNITY_LIGHTMODEL_AMBIENT.xyz * tex2D(_MainTex,i.uv).rgb;

                //使用法線在燈光方向的投影長度作為透明度
                return fixed4(c,1-dot(worldNormal,worldLightDir));
            }
                              
            ENDCG
        }      
	}

    Fallback "Specular"
}