Rendering ghosts with Depth Buffer magic

Here's a bit more technical post! Recently while working on my iPhone game, specifically on the last world which if you'll play the game you'll discover being an haunted house, I had to find a solution to draw ghosts on the screen!

Well, it's easy, just let the rendering engine draw them as you normally would, one might think. Unfortunately, it's not so obvious! At least if you want to make the ghost transparent and not opaque.

The reason behind this is because if you render the ghost body as transparent, you end up seeing not only what's behind the ghost but also what's INSIDE the ghost himself, like his mouth, teeth, etc, something you probably don't want to see.

Here's an example from a game I loved playing, Luigi's Mansion:


If this scary ghost turns its back to you, the head will remain transparent but you can't see his pacifier nor his eyes. The trick resides in the Depth Buffer which is basically a two dimensional array of floating point numbers which stores the per-pixel distance of one given object to the camera. If the object you draw next is behind the one you just drawn it is said that it will fail the depth-test, hence it will not be visible. (For a longer explaination you can read here: http://en.wikipedia.org/wiki/Z-buffering)

The trick to render this ghost correctly is to draw the body first as transparent while still writing in the depth buffer (something which is normally disabled for transparent objects) and only after draw all the rest. If the pacifier is behind the body it will fail the depth-test and not be drawn at all, even if the body is transparent.

Pretty cool, isn't it? :)

Nessun commento:

Posta un commento