Code Problem Solved: How to Implement z-order Rendering

If you’ve dealt with cascading style sheets (CSS) in web design, then you might be aware of z-index (also known as z-order). This special attribute tells the web browser to render elements in a certain order. But specifically in webpages, a z-index can range from 0 to 99, where 0 is the farthest back element (it is rendered first) and 99 is the front most element (it is rendered last). All is well when the software’s already working for you, but what about in game development? Here’s a way…

Game engines, like most rendering implementations, runs on loops. Loops usually just increment one-by-one through each object. Therefore, in the simplest of rendering loops, elements can be drawn starting from the first to the last. However, in games, there will be times when as a designer you want to create a sense of depth. This is when it’s important to be able to draw certain objects before or after other objects, creating a sense of layering or going “around” something.

NOTE: THIS IS GENERIC PSEUDO-CODE!!!
//object members
object.location
object.zOrder

//determine object's zOrder so you know when to draw by using a nest loop
//internally, each object has its own index inside an array or collection
//however, it might not be efficient to swap entire objects unless they were small
//and swapping only zOrder indexes is way faster

//ideally, if you want to draw all available objects, the zOrder maximum value would
//the total count of objects
zOrderMax = objectArray.length

'sorting loop
for s = 0 to objectArray.length
  if objectArray[0].location > objectArray[s].location And objectArray[0].zOrder < objectArray[s].zOrder then
    swapZOrders()
  end if
next

'drawing loop
for i = 0 to zOrderMax
  for j = 0 to objectArray.length
         if objectArray[j].zOrder = i then
              drawObject()
         end if
  next
next

I don't want to go into any more detail, but you will have to define your own conditions in the sorting loop. For example, when an object is meant to be "in front" of another, you would check if the top of that object has moved below the top of the test object. Or to use more world-based logic you could test the bottom of the objects.

Also, be mindful that you might not want to be nesting that sorting loop and have a kazillion cross-comparision of objects. To best optimize the computations, if you are only moving manually one object, compare only that one object to the rest of the objects in the array. Yes, unfortunately, that means the other objects might have to be stationary or you'll have to devise some clever way to test their zOrders for a more lively or more accurate animation.

Tags: , , , , , , , , , , ,

Comments are closed.