# 【Shader练习-双面材质】

全屏显示

包括了以下练习内容:

  1. 法线和视线。
  2. 纹理采样。

TwoFaceShader.shader

Shader "Unlit/TwoFaceShader"
{
    Properties
    {
        _FrontTex ("FrontTex", 2D) = "white" {}
        _BackTex ("BackTex", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100
        Cull Off

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

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

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
                float3 nDirWS : TEXCOORD1;
                float4 posWS : TEXCOORD2;
            };

            sampler2D _FrontTex;
            sampler2D _BackTex;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                o.nDirWS = UnityObjectToWorldNormal(v.normal);
                o.posWS = mul(unity_ObjectToWorld,v.vertex).xyzw;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // 世界空间下的摄像机方向
                float3 vDirWS = normalize(_WorldSpaceCameraPos.xyz - i.posWS.xyz);
                
                // 模型法线与眼睛视线方向的点积,法线和视线同向 > 0 反向 < 0
                float ndv = dot(i.nDirWS,vDirWS);

                if(ndv > 0){
                    fixed4 col_b = tex2D(_BackTex, i.uv);
                    return col_b;
                }else{
                    fixed4 col_f = tex2D(_FrontTex, i.uv);
                    return col_f;
                }
            }
            ENDCG
        }
    }
}