I am building a 2D game using sprites. I'd like to use the z-buffer to aid with shading.
For that I need Unity to write only opaque pixels to the z-buffer (aka depth buffer). In Unity, sprites are built up of polygons, and it is writing these entire polygons, including the transparent pixels, to the depth buffer.
This is the shader I'm using (with some junk added while trying to get this to work) http://pastebin.com/khprCUA0
I have tried
- AlphaTest Greater 0
- alphatest:MyAlphaTestVar
- the
discard
keyword - Cg's
clip
function - I suspected that a lighting pass might be writing the depths so I added
novertexlights
andnoambient
I would suspect that AlphaTest prevents transparent pixels from having any effect on the frame or depth buffer (as suggested here), but they still do write to the depth buffer!
The screenshot below shows the inaccurate shapes of objects in the Z-buffer. The king and tree have become blobs because even their transparent pixels were updated in the Z-buffer (drawn using http://willychyr.com/2013/11/unity-shaders-depth-and-normal-textures/):
Compare this to the "correct" shape of the objects in the regular view:
How do I get Unity to not write transparent pixels to the z-buffer?
EDIT:
Unity 5's frame debugger is turning out to be a miracle! Turns out the "Depth Texture" is actually rendered in a separate pass before all other geometry. And I'm having trouble finding out how to use RenderType to include/exclude certain objects from this pass.