I am trying to achieve the effect described in this question.
I have made three sprites, materials and shaders.
Here are my shaders:
Shader "Custom/BlueArea" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
}
SubShader {
Tags { "RenderType"="Opaque"}
LOD 200
Pass {
Stencil {
Ref 1
Comp always
Pass replace
}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
struct appdata {
float4 vertex : POSITION;
};
struct v2f {
float4 pos : SV_POSITION;
};
v2f vert(appdata v) {
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
return o;
}
half4 frag(v2f i) : COLOR {
return half4(0,0,1,1);
}
ENDCG
}
}
FallBack "Diffuse"
}
This is the equivalent of “Area 2” in the first question I linked.
Then we have the shader for the player’s small box:
Shader "Custom/RedPlayer" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
}
SubShader {
Tags { "RenderType"="Opaque"}
LOD 200
Pass {
Stencil {
Ref 1
Comp equal
}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
struct appdata {
float4 vertex : POSITION;
};
struct v2f {
float4 pos : SV_POSITION;
};
v2f vert(appdata v) {
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
return o;
}
half4 frag(v2f i) : COLOR {
return half4(1,0,0,1);
}
ENDCG
}
}
FallBack "Diffuse"
}
And the shader for the large box:
Shader "Custom/PurplePlayer" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
}
SubShader {
Tags { "RenderType"="Opaque"}
Pass {
Stencil {
Ref 1
Comp equal
}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
struct appdata {
float4 vertex : POSITION;
};
struct v2f {
float4 pos : SV_POSITION;
};
v2f vert(appdata v) {
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
return o;
}
half4 frag(v2f i) : COLOR {
return half4(1,0,1,1);
}
ENDCG
}
}
FallBack "Diffuse"
}
This is what I currently see:
I am expecting to only see the red and purple blocks drawn where they overlap the blue area.
I understand that in its current state, the red and purple shaders both function the same, but they render even while outside of the blue area. I cannot figure out why this is. Could anyone with a good understanding of shaders tell me why this technique is failing?