Quick Tip: Depth Management With the Display List in AS3


This Cyber Monday Tuts+ courses will be reduced to just $3 (usually $15). Don't miss out.

Moving items to top and bottom of the display list can be very useful when developing games and applications. Learn to easily manage depth using this QuickTip.

Final Result Preview

Let's take a look at the final result we will be working towards:

Click an icon to select it and bring it to the top of the display list, then use the two buttons to move it lower in the hierarchy.

Step 1: Brief Overview

Using ActionScript 3 we'll learn how to manage top, bottom and intermediate levels of depth.

Step 2: Set Up Your Flash File

Launch Flash and create a new Flash Document, set the stage size to 320x200px and the frame rate to 24fps.

Step 3: Interface

This is the interface we'll be using, a series of buttons in stage that will activate the depth change.

Convert the characters to Button and name the Tuts+ logos like this: nt, at, pt. For the other buttons the instance names are bottomB and oneB.

Step 4: ActionScript

Create a new ActionScript Class (Cmd+N), save the file as and write the following lines, please read the comments in the code to fully understand the class behavior.

	import flash.display.Sprite;
	import flash.filters.GlowFilter;

	public final class Main extends Sprite
		private var lastItem:Sprite; //stores the last clicked sprite
		private var glow:GlowFilter = new GlowFilter(0xFF9900);// a glow filter to highlight the last item
		public final function Main():void
			lastItem = nt; //the top item at start
		private final function addListeners():void
			at.addEventListener(MouseEvent.MOUSE_DOWN, up);
			pt.addEventListener(MouseEvent.MOUSE_DOWN, up);
			nt.addEventListener(MouseEvent.MOUSE_DOWN, up);
			oneB.addEventListener(MouseEvent.MOUSE_UP, downOne);
			bottomB.addEventListener(MouseEvent.MOUSE_UP, bottom);
		private final function up(e:MouseEvent):void
			lastItem.filters = []; //remove last filter if any
			lastItem = as Sprite; //stopre last clicked item
			lastItem.filters = [glow]; //apply filter
			setChildIndex(lastItem, numChildren - 1);//get next highest depth
		private final function downOne(e:MouseEvent):void
			if(getChildIndex(lastItem) != 0)//prevent out of bounds
				setChildIndex(lastItem, getChildIndex(lastItem) - 1);//down one level
		private final function bottom(e:MouseEvent):void
			setChildIndex(lastItem, 0);//bottom

Step 5: Document Class

Add the class name to the Class field in the Publish section of the Properties panel to associate the FLA with the Main document class.


Use what you learned in this QuickTip in your games and applications!

I hope you liked this Quick Tip, thank you for reading!