# 【Shader练习-游戏王闪卡】

全屏显示

_FlashTex 纹理:

Markdown 图片

FlashCardShader.shader

Shader "Unlit/FlashCardShader"
{
    Properties
    {
        _FrontTex ("FrontTex", 2D) = "white" {}
        _BackTex ("BackTex", 2D) = "white" {}
        _FlashTex ("FlashTex", 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;
            sampler2D _FlashTex;

            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);

                    //ndv 0 ~ -1
                    float offsetX = ndv * 0.5;// 0~ -0.5
                    float simX = i.uv.x * 0.5 - offsetX;
                    fixed4 col_fl = tex2D(_FlashTex, float2(simX,0.1f));
                    col_fl *= 0.5f;
                    return col_f * 0.85 + col_fl;
                }
            }
            ENDCG
        }
    }
}