# Mixing z-buffer and spritebatch to simulate 3d behaviour

Hello everyone,
is there any standard way i can add a “z-buffer” channel to a spritebatch.draw so that it’s sampled value is added to the z-buffer?

This way i could simulate “vertical” objects in a “horizontal” top-down view without the need to use 3d camera and quads.
Of course i cannot use a simple sorting algorithm because
lower ground needs to be at Z=1,
vertical object needs to be at Z=2,
higher ground needs to be at Z=3.

Don’t forget that spritebatch.Draw has a depth parameter in some of its overloads and that can sort by depth. Make sure you use the SpriteSort mode that sorts by depth in the begin call.

So if your setting each drawing and know its z ground just set that for depth.

If its dependent on were you position it by height divide the position.Y by the windows Height and set that to depth.

If its a mix of both make a algorithm and set that for depth.

Or you can make a drawing list of your own class that takes all the types of parameters that spritebatch takes and sort it yourself by depth then pass it in order but spritebatch is pretty efficient at doing this. If this is really about getting it into the depth buffer i think you can just flip it on from the graphicsdevice. SpriteBatch is in reality just drawing 3d quads.

Yeah, unfortunately i know enough about sorting to know that what i want to do is not possible without adding a value to the z-buffer. To be more precise, i need to add a gradient to “emulate” a vertical item in a horizontal world.

So, from my drawing i’d add 0 to the bottom of the tree so that it sits below the bottom-placed high ground, and 2 to the top so that the top part of the tree is above the top-placed hight ground…

Use the y-coordinate of a sprite as the depth parameter and use `SpriteSortMode.FrontToBack` to sort the sprites by depth. (Note that the depth parameter can only be values from 0 to 1 for `SpriteBatch`, so divide the y-coordinate by the screen height.) This will make sprites with smaller depth values, hence smaller y-coordinate values, be drawn first. I call this technique the “Y-flip”. You can think of it as having a horizontal line for each sprite where lines closer to the top of the screen are drawn before lines closer to the bottom of the screen. The neat thing is that the y-coordinate of a sprite could change on a frame-per-frame basis, allowing sprites to be positioned correctly even when they move.

Here is your original image with add lines in yellow at the bottom of each sprite using this method.

I can imagine the reason why a depth-buffer is not used by default (sorting the sprites on the CPU each frame is not performant) is that there might be problems with Z-fighting when several sprites have the same depth.