How to add texture offset support to this shader
Hi, I am not any way experienced with shaders. I honestly want to avoid the coding part of shaders and only use shader graph, however this one special case cannot be done with shader graph. I've used this guide https://nielson.dev/2015/12/splatter-effects-in-unity-using-the-stencil-buffer in order to use Unity stencil with a 9 sliced sprite and I've gotten the effect that I want, except that I need to be able to scroll the texture being masked within it.
I know that there is something you need to add to the shader based on the results I've come up with from searching, however I am in no way experienced enough to know how to implement these. I tried implementing code from this answer https://answers.unity.com/questions/885316/texture-offset-not-working-because-of-shader.html and it allowed me to offset the texture but for some reason there was some weird alpha and color glitches with the way it worked which I also do not know how to fix.
Any help would be appreciated.
This is the exact shader I am using
Shader "Stencil Mask/ToBeMasked"
{
Properties
{
[PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
_Color ("Tint", Color) = (1,1,1,1)
[MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
_AlphaCutoff("Alpha Cutoff", Range(0.01, 1.0)) = 0.01
}
SubShader
{
Tags
{
"Queue"="Transparent"
"IgnoreProjector"="True"
"RenderType"="Transparent"
"PreviewType"="Plane"
"CanUseSpriteAtlas"="True"
}
Cull Off
Lighting Off
ZWrite Off
Blend One OneMinusSrcAlpha
Pass
{
Stencil
{
Ref 5
Comp Always
Pass Replace
}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile _ PIXELSNAP_ON
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
float4 color : COLOR;
float2 texcoord : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
half2 texcoord : TEXCOORD0;
};
fixed4 _Color;
fixed _AlphaCutoff;
v2f vert(appdata_t IN)
{
v2f OUT;
OUT.vertex = UnityObjectToClipPos(IN.vertex);
OUT.texcoord = IN.texcoord;
OUT.color = IN.color * _Color;
#ifdef PIXELSNAP_ON
OUT.vertex = UnityPixelSnap (OUT.vertex);
#endif
return OUT;
}
sampler2D _MainTex;
sampler2D _AlphaTex;
float _AlphaSplitEnabled;
fixed4 SampleSpriteTexture (float2 uv)
{
fixed4 color = tex2D (_MainTex, uv);
if (_AlphaSplitEnabled)
color.a = tex2D (_AlphaTex, uv).r;
return color;
}
float4 _MainTex_ST;
fixed4 frag(v2f IN) : SV_Target
{
fixed4 c = SampleSpriteTexture (IN.texcoord) * IN.color;
c.rgb *= c.a;
// Discard pixels below cutoff so that stencil is only updated for visible pixels.
clip(c.a - _AlphaCutoff);
return c;
}
ENDCG
}
}
}
Answer by Blakiemon · Nov 28, 2020 at 04:19 AM
Hi, just in case anyone else who sees this and doesn't know anything about shaders has a similar problem, you can still mask sprites with Stencil that have a default material. (Even with Unity's 2D experimental lighting!) Just make sure to set the mask interaction mode to something other than none.