- Home /
How to do a sprite shader with masking for individual sprites ?
Hi everyone,
Can someone help me how to modify the uv in this sprite shader to get the expected result.Here is my simple unlit sprite shader code.
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile DUMMY PIXELSNAP_ON
//Color sampler
fixed4 _Color;
//Texture samplers
sampler2D _MainTex;
sampler2D _MaskTex;
struct appdata_t
{
float4 vertex : POSITION;
float4 color : COLOR;
float2 texcoord : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
half2 texcoord : TEXCOORD0;
};
//The vertex shader
v2f vert(appdata_t IN)
{
v2f OUT;
OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
OUT.texcoord = IN.texcoord;
OUT.color = IN.color * _Color;
#ifdef PIXELSNAP_ON
OUT.vertex = UnityPixelSnap (OUT.vertex);
#endif
return OUT;
}
//The fragment shader
fixed4 frag(v2f IN) : COLOR
{
//Get the main texture color
float4 FinalColor = tex2D (_MainTex,IN.texcoord);
//Get alpha from the alpha texture
FinalColor.a = tex2D(_MaskTex,IN.texcoord).a;
//Return the final color
return FinalColor;
}
ENDCG
Lets say i have a 512x512 size with sprites in grid as 128x128 which gives 16 sprites in total.For all the 16 sprites,I'm applying one material with this shader and a circular mask texture.Now the mask should apply for each sprites. The below image will explain what i need in detail.
Thanks for any help in advance .... :-)
Answer by komodor · Sep 29, 2015 at 07:16 AM
not sure right now and i don't have time to test it right now, i remember you need to mutliply the rgb with alpha
FinalColor.rgb *= FinalColor.a;
return FinalColor;
i'll get to that later if i am wrong
@komodor Hi,thanks for the help.But that wont give me the expected output.See the alpha blending is working fine.Its the uv which have to be altered.I actually figured it out.$$anonymous$$y quad mesh requires 2 uv channels.First uv for the maincolor will have value based on atlas but the second uv value will be full 0,0 to 1,1 to map the entire mask texture and the alpha have to be chose from that
//Get the main texture color
float4 FinalColor = tex2D (_$$anonymous$$ainTex,IN.texcoord);
//Get alpha from the alpha texture to second uv channel
FinalColor.a = tex2D(_$$anonymous$$askTex,IN.uv2).a;
//Return the final color
return FinalColor;
Your answer
![](https://koobas.hobune.stream/wayback/20220612035305im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Sprites consisting of two packed textures 0 Answers
Accessing a second texture's offset in a modified sprite shader 0 Answers
Efficient way to keep a fixed rotation for sprite? 0 Answers
Sprite shader relative UV's 0 Answers
Sprite not visible from behind 0 Answers