[SOLVED] 2D z-culling?

Hello.

Getting into 3D I was wondering if there exists a similar efficient algorithm for drawing 2d sprites with z-culling. Ie. not drawing things that are behind other things unnecessarily.

Is this available in Java2D? What I’ve been doing previously is just drawing objects (and their images) based on their depth value that I store in an arrayList ( and sort as new objects are added to keep it in order ). This has worked fine… to some extent.

What about when using an OpenGL library, is it as simple as turning some z-culling switch ON and giving Textures a depth value of some sorts?

Thanks,
jon

The way you’re doing it in Java2D is pretty much the right way – draw back to front, don’t bother drawing what’s obscured by something in front. With OpenGL, it is as easy as turning on depth testing and assigning z-values to the geometry (not the textures), and it’ll all get sorted out in the z-buffer. Complex scenes will still want to do their own occlusion culling, but that’s usually not necessary for anything 2D.

You need to also clear the depth buffer along with the color buffer:

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

And make sure the z value is within near and far defined in glOrtho. You might also want to enable alpha testing depending on what you’re rendering.

I personally just render in order with lists/sorting, as I haven’t found it to be a CPU bottleneck in my simple games.

Mostly you don’t want to use the depth buffer though, because you are likely going to be drawing transparent sprites with nice antialised edges. So although you can cheat if you’re doing super retro (in which case you’re probably wasting your time with this optimisation anyway!) and use something called the alpha test to draw the equivalent of cookie-cutter or “one bit” transparency with the depth buffer successfully, use any translucent sprites and it won’t work.

tl;dr - don’t use the depth buffer, sort your sprites manually back to front before rendering.

Cas :slight_smile: