Pages

Friday, 25 December 2015

A simple mask shader for Unity3D

Let me share a simple mask shader which takes two texture the main texture and the mask texture. Main texture is rendered if the mask texture does not have alpha as 0.

Shader "TRSquareLab/Mask" {

     Properties {
          // Main Texture
          _MainTex ("Texture", 2D) = "white" { }
          
          // Mask texture, color from main texture will be applied if
          // the mask texture does not have alpha as 0
          _MaskTex ("Mask", 2D) = "white" { }     
     }
     
     SubShader {
          Pass
               {
                    CGPROGRAM
                    
                    #pragma vertex vert
                    #pragma fragment frag
                    #include "UnityCG.cginc"
               
                    sampler2D _MainTex;
                    sampler2D _MaskTex;
               
                    struct v2f {
                         float4 pos : SV_POSITION;
                         float2 uv : TEXCOORD0;
                    };
                    
                    float4 _MainTex_ST;
                    
                    v2f vert (appdata_base v)
                    {
                         v2f o;
                         o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
                         o.uv = TRANSFORM_TEX (v.texcoord, _MainTex);
                         return o;
                    }
                    
                    fixed4 frag (v2f i) : SV_Target
                    {
                         fixed4 texcol = tex2D (_MainTex, i.uv);
                         fixed4 maskcol = tex2D (_MaskTex, i.uv);
                         // Discard the pixel if the alpha is 0
                         if (maskcol.a == 0) {
                              discard;
                         }
                         // Else return the main texture color
                         return texcol;
                    }
                    
                    ENDCG
               }
     }
     
     FallBack Off
}


No comments:

Post a Comment