Monday, June 14, 2010

Easy Depth Sorting in Actionscript 3

I'm working on an ActionScript 3 project, and I needed a way to height-sort objects on the screen (so that elements further down the screen are drawn on top of elements further back). Thanks to a little web searching and my own hacking, here's an easy solution to the problem. It's called "DepthSort Space", and it's a movie clip that depth sorts all its children each frame. Currently, it uses bubble sort on the list, but if speed is of the essence, you could probably use some other sorting mechanism.

package {

import flash.display.*;

public class DepthSortSpace extends MovieClip {

public function DepthSortSpace() {
this.addEventListener( Event.ADDED_TO_STAGE, this.addedToStage, false, 0, true );

private function addedToStage( e:Event ) {
this.stage.addEventListener( Event.ENTER_FRAME, this.enterFrame, false, 0, true );

private function sortDisplayList():void {
var len:uint = numChildren;
var i,j;
for( i=0; i < len-1; i++ )
for (j=i+1; j < len; j++)
if ( getChildAt(i).y > getChildAt(j).y ) this.swapChildrenAt( i, j );

private function enterFrame(e:Event) {


To use this, just make a new symbol, and set its class to DepthSortSpace (or subclass DepthSortSpace as your movie clip if you're already adding custom code for it). Then, add any objects you want to depth sort as children of this movie clip. It will handle it automatically.

1 comment:

Anonymous said...

Dude, quicksort, radixsort, mergesort are vastly superior to bubblesort : bubblesort is n squared, and quicksort is average case nlogn. For very small n, bubblesort may be fast enough, but quicksort typically does much better: the lynchpin of quicksort is finding a good pivot: if your data is close to sorted, you may consider insertion sort.

Hope Halloween is fun... Sorry I can't be there to operate the magic mirror! I am actually getting my toe x-rayed in the doctors office, so I thought I'd check your blog.