HIde 3D objects behind segmented pixels of 2D texture
I'm trying to hide 3D objects using a texture. I want only few pixels ( segmented pixels) to occlude the 3D behind it.
For example in below image I have a black and white texture where I'd want the white part of the texture to occlude any 3D behind it. Black and white colors are just for representation . In reality, the white pixels would be transparent but will hide anything behind it (occlusion) whereas the black pixels would also be transparent but will not hide anything behind it, i.e., it won't render anything.
I have used occlusion shaders in the past on 3D objects which works just fine but in this case i want to use occlusion using only certain pixels of a texture.
I have looked into stencil buffers and assuming my understanding is right, it involves setting the stencil buffer on the objects that needs to be occluded( cube). However, I have no control over the 3D objects since they are AR assets that are downloaded dynamically. So I cannot edit the shader code running on those objects.
I'm also very new into shader programming.
Answer by BastianUrbach · Jun 16, 2021 at 10:39 AM
You can hide objects by placing something in front of them that is rendered before them and only writes depth, but no color. To control it with a texture, you can simply clip black pixels so that they don't write anything at all:
Shader "Unlit/Occlude" {
Properties {
_MainTex ("Texture", 2D) = "white" {}
}
SubShader {
Tags { "Queue"="Geometry-100" } // Draw before everything else
ColorMask 0 // Only write depth
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;
float4 _MainTex_ST;
v2f vert (appdata v) {
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}
float4 frag (v2f i) : SV_Target {
clip(tex2D(_MainTex, i.uv) - 0.5);
return 0;
}
ENDCG
}
}
}
Thank you for the code. Clipping black pixels did work however I had to add Blend SrcAlpha OneMinusSrcAlpha
just before the Pass begins. I found this in some other shader code. Reading up more on this !
That shouldn't be necessary. The shader doesn't write colors at all (ColorMask 0). Blending should have no effect.
Your answer
Follow this Question
Related Questions
Glowing outline with occlusion 0 Answers
how to make dynamic textures for multiple objects? 0 Answers
Something wrong with the cut out feature of the standard shader? 0 Answers
How can I apply texture through shader on sprite without streching? 0 Answers
How do i pass a Texture 2D Array into a function as a parameter 0 Answers