【Unity Shader】 Alpha测试

介绍

Alpha测试:符合条件的像素显示出来,不符合的丢掉

一、fixed function shader的透明通度测试

ShaderLab: Legacy Alpha Testing

语法
  1. 关闭Alpha测试
AlphaTest Off

渲染所有的像素(默认)或者…
2. 开启Alpha测试

AlphaTest comparison AlphaValue

设置alpha测试,根据alpha值筛选符合条件的像素进行渲染

  1. Comparison Alpha测试的比较命令

    • Greater
      Only render pixels whose alpha is greater than AlphaValue.
    • GEqual
      Only render pixels whose alpha is greater than or equal to AlphaValue.
    • Less
      Only render pixels whose alpha value is less than AlphaValue.
    • LEqual
      Only render pixels whose alpha value is less than or equal to from AlphaValue.
    • Equal
      Only render pixels whose alpha value equals AlphaValue.
    • NotEqual
      Only render pixels whose alpha value differs from AlphaValue.
    • Always
      Render all pixels. This is functionally equivalent to AlphaTest Off.
    • Never
      Don’t render any pixels.
开启alpha测试,只渲染alpha值大于0.5的像素:

这里写图片描述

Shader "Hidden/alphatest"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        // No culling or depth
        Cull Off ZWrite Off ZTest Always

        // alphatest
        // AlphaTest Off
        AlphaTest Greater 0.5
        Pass
        {
            SetTexture[_MainTex]
        }
    }
}

二、可编程shader的透明度测试

ShaLab的AlphaTest命令在shader2.0中是不起作用的。
由于可编程shader会对纹理采样,可以直接操作纹理的透明通道值,因此也不需要AlphaTest命令。而fixed function shader不会纹理采样,只能依靠AlphaTest命令进行Alpha测试。

同样,开启alpha测试,只渲染alpha值大于0.5的像素:

这里写图片描述

Shader "Hidden/alphatest2"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        // No culling or depth
        //Cull Off ZWrite Off ZTest Always

        Blend SrcAlpha OneMinusSrcAlpha
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

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

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            sampler2D _MainTex;

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                if(col.a < 0.5 )
                {
                    return fixed4(0,0,0,0);
                }else
                {
                    return col;
                }
                return col;
            }
            ENDCG
        }
    }
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页