Unity镂空遮罩shader代码,支持圆形和矩形
时间: 2024-09-18 17:09:25 浏览: 245
Unity中实现镂空遮罩Shader通常会涉及到Alpha Blending(透明混合)和Masking(掩模)。下面是一个简单的示例,展示如何创建一个基本的镂空遮罩Shader,可以处理圆形和矩形形状。假设我们已经有了一个基础的Sprite Renderer组件,我们将创建一个名为`UIMaskedShader`的Shader:
```glsl
Shader "Custom/UIMaskedShader" {
Properties {
_MainTex ("Texture", 2D) = "white" {}
_Color ("Color", Color) = (1,1,1,1)
_MaskTex ("Mask Texture", 2D) = "white" {}
}
SubShader {
Tags { "Queue"="Transparent" "RenderType"="Opaque" }
LOD 100
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;
};
sampler2D _MainTex;
sampler2D _MaskTex;
fixed4 _Color;
v2f vert (appdata v) {
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
fixed4 frag (v2f i) : SV_Target {
fixed4 col = tex2D(_MainTex, i.uv);
fixed4 mask = tex2D(_MaskTex, i.uv);
// Alpha blending using the mask texture as a threshold
col.a *= step(mask.r, 0.5); // For circular masks (0.5 alpha value)
// Adjust for rectangular masks if needed (mask.r would be different)
return lerp(col, fixed4(0,0,0,0), col.a) * _Color; // Blend with transparent color when alpha is low
}
ENDCG
}
}
FallBack "Diffuse"
}
// To use for a circular mask:
void DrawMesh(....., Material mat, int iVert, int iNumVertices, int iStartIndex, int iNumIndices) {
mat.SetTexture("_MaskTex", yourCircularMaskTexture);
.....
}
// For a rectangular mask:
void DrawMesh(....., Material mat, int iVert, int iNumVertices, int iStartIndex, int iNumIndices) {
mat.SetTexture("_MaskTex", yourRectangularMaskTexture);
.....
}
```
在这个例子中,你需要提供两个纹理贴图,一个是主颜色纹理 `_MainTex`,另一个是镂空掩码纹理 `_MaskTex`。`step`函数用于圆形遮罩,当像素值低于0.5(对于256色深度的图像,0.5对应半透明)时,将其alpha值设为0,达到镂空效果。
阅读全文
相关推荐














