Return to Kroll Design home page

Flash Tutorials (with .FLA files included)

« Return

ActionScript 3

Using setChildIndex to set the depth (stacking order) of sprites

When multiple sprites are on the stage and some of them overlap each other, which ones upstage other ones is determined by their depth, or stacking order. The sprite at the bottom of the stack (farthest away) is at level 0. So it will be concealed by any sprites that are on top of it. The number of display objects on the stage at any given time is indicated by the Flash variable numChildren, so since the counting starts at zero, the depth number of the topmost sprite is numChildren-1. This example shows 3 circles. When you click or shift click on a circle, an event is called, which uses the setChildIndex method to assign a new depth to the sprite.

Download the FLA file

var sprite1:Sprite = new Sprite();
var sprite2:Sprite = new Sprite();
var sprite3:Sprite = new Sprite();
const offset = 40;
const startingPositionX = 100;
const startingPositionY = 70;

sprite1.buttonMode = true;
sprite2.buttonMode = true;
sprite3.buttonMode = true;;,0,50);
sprite1.x = startingPositionX; sprite1.y = startingPositionY;;,0,50);
sprite2.x = startingPositionX - offset; sprite2.y = startingPositionY + offset;;,0,50);
sprite3.x = startingPositionX + offset; sprite3.y = startingPositionY + offset;


sprite1.addEventListener(MouseEvent.CLICK, changeSpriteDepth);
sprite2.addEventListener(MouseEvent.CLICK, changeSpriteDepth);
sprite3.addEventListener(MouseEvent.CLICK, changeSpriteDepth);

function changeSpriteDepth(myEvent:MouseEvent):void
var clickedCircle:Sprite = Sprite(myEvent.currentTarget);
var newPosition:uint;

if (myEvent.shiftKey == true)
		newPosition = 0;
	  newPosition = numChildren - 1; // numChildren is a Flash variable indicating
		                               // the number of objects in display list

setChildIndex(clickedCircle, newPosition);

« Return

©2012 Kroll Design    781.910.3694
Last modified: 12/31/1969 7:00 PM