AS3 Depth sorting made easy

The plot thickens and you find yourself in a dense forest and pack of wolves surrond you…

And if you are a neophyte Flash coder you are in middle of depth sorting nightmare. How does one make wolves and trees look correct so that when a wolf moves behind a tree, it disappears, and when a wolf is in front of tree, the tree is not seen over the wolf?

This is actually quite easy, as long as the objects are considered to be “point-like” ( they dont have any real volume), and the view is traditional isometric view.  Then all that is needed is that the drawing order of objects is set so that objects are rendered based on their vertical position in the view. Items on the top are rendered first, items on the bottom of the view are rendered last, front of earlier placed items.

In practice we set up an array containing all objects, and in game loop we reorder the array based on y value of objects, and then add the items to scene:

  • viewItems is an array that has all objects in scene pushed into it.
  • Objects have variable viewItemY

viewItems.sortOn("viewItemY", Array.NUMERIC);
for(i=0; i<viewItems.length; i++)
{
scene.addChild(viewItems[i].viewItem);  //
}

Suprisingly, you dont even need to remove the items from the scene, addChild() will remove the item and put it back, in correct order.

Above I stated that y value of object is used… so why use another variable, viewItemY here? Well, maybe you would like to have items that appear over everything else, like roofs. Then you can manipulate the drawing order of item, like this:

if(element is Roof)
{
element.viewItemY = element.y+ 10000;
// roofs are positioned above all other stuff
}

So, depth sorting in ActionScript 3 is easy!

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

3 Comments »

 
 

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>