Unity shader实现遮罩效果

编辑: admin 分类: c#语言 发布时间: 2022-03-12 来源:互联网

本文实例为大家分享了Unity shader实现遮罩效果的具体代码,供大家参考,具体内容如下

效果:

shader代码:

Shader "Custom/Mask" {
 Properties {
 _MainTex ("Base (RGB)", 2D) = "white" {}//目标图片,即需要被遮罩的图片
 _MaskLayer("Culling Mask",2D) = "white"{}//混合的图片,设置为白色的图片,任何颜色与白色混合,其颜色不变
 _Cutoff("Alpha cutoff",Range(0,1)) = 0
 }
 SubShader {
 Tags { 
 "Queue"="Transparent" 
 }//渲染队列设置为 以从后往前的顺序渲染透明物体
 Lighting off //关闭光照
 ZWrite off //关闭深度缓存
 Blend off //关闭混合
 AlphaTest GEqual[_Cutoff] //启用alpha测试

 Pass{
 SetTexture[_MaskLayer]{combine texture}//混合贴图
 //混合贴图,previous为放置在前一序列这样在进行AlphaTest的时候会以这个图片为主来进行混合
 SetTexture[_MainTex]{combine texture,previous}
 } 
 }
}

新建一个材质球,然后将目标图片和遮挡图片赋予一下,即可看到效果

小编再为大家分享另一段代码:Unity shader无锯齿遮罩效果,忘记作者名字了,感谢这位朋友的分享。

【来源:自由互联:http://www.yidunidc.com/usa.html 欢迎留下您的宝贵建议】

这个Shader可以用于UGUI制作头像框遮罩,没有锯齿,非常nice

Shader "Custom/CircleMask" {
 Properties {
  _MainTex ("MainTex", 2D) = "white" {}
  _MaskTex ("MaskTex", 2D) = "white" {}
  [HideInInspector]_Cutoff ("Alpha cutoff", Range(0,1)) = 0.5
  //MASK SUPPORT ADD
  _StencilComp ("Stencil Comparison", Float) = 8
  _Stencil ("Stencil ID", Float) = 0
  _StencilOp ("Stencil Operation", Float) = 0
  _StencilWriteMask ("Stencil Write Mask", Float) = 255
  _StencilReadMask ("Stencil Read Mask", Float) = 255
  _ColorMask ("Color Mask", Float) = 15
  //MASK SUPPORT END
 }
 SubShader {
  Tags {
   "IgnoreProjector"="True"
   "Queue"="Transparent"
   "RenderType"="Transparent"
  }
  //MASK SUPPORT ADD
  Stencil
  {
   Ref [_Stencil]
   Comp [_StencilComp]
   Pass [_StencilOp]
   ReadMask [_StencilReadMask]
   WriteMask [_StencilWriteMask]
  }
  ColorMask [_ColorMask]
  //MASK SUPPORT END
  Pass {
   Name "FORWARD"
   Tags {
    "LightMode"="ForwardBase"
   }
   Blend SrcAlpha OneMinusSrcAlpha
   ZWrite Off
   CGPROGRAM
   #pragma vertex vert
   #pragma fragment frag
   #define UNITY_PASS_FORWARDBASE
   #include "UnityCG.cginc"
   #pragma multi_compile_fwdbase
   #pragma only_renderers d3d9 d3d11 glcore gles
   #pragma target 3.0
   uniform sampler2D _MainTex; uniform float4 _MainTex_ST;
   uniform sampler2D _MaskTex; uniform float4 _MaskTex_ST;
   struct VertexInput {
    float4 vertex : POSITION;
    float2 texcoord0 : TEXCOORD0;
   };
   struct VertexOutput {
    float4 pos : SV_POSITION;
    float2 uv0 : TEXCOORD0;
   };
   VertexOutput vert (VertexInput v) {
    VertexOutput o = (VertexOutput)0;
    o.uv0 = v.texcoord0;
    o.pos = UnityObjectToClipPos( v.vertex );
    return o;
   }
   float4 frag(VertexOutput i) : COLOR {
////// Lighting:
    float4 _MainTex_var = tex2D(_MainTex,TRANSFORM_TEX(i.uv0, _MainTex));
    float3 finalColor = _MainTex_var.rgb;
    float4 _MaskTex_var = tex2D(_MaskTex,TRANSFORM_TEX(i.uv0, _MaskTex));
    return fixed4(finalColor,_MaskTex_var.a);
   }
   ENDCG
  }
 }
 FallBack "Diffuse"
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持海外IDC网。