Understanding how AS3 manages Depths

This tutorial will explain you how to manage AS3 sprites and depths, and what’s changed from AS2 to AS3.

In every Actionscript version, when two movieclips (or objects, shapes, texts…) overlap, the one with the greater depth stands in front of the other. You can think about depth as a Z coordinate.

The first difference between AS2 and AS3 is that AS2 allows you to leave “holes” in depths.

For example, you can declare the first object with a depth of 2 and the second one with a depth of 200… no matter if there isn’t any object with a depth between 3 and 199. In AS3, this is no longer possible.

To add an object to the stage, you must use addChild(object_name).
addChild() assigns the first free depth available, just like AS2 MovieClip.getNextHighestDepth()

So let’s add some objects to a movie:

package {
	import flash.display.Shape;
	import flash.display.Sprite;
	public class depths extends Sprite {
		public function depths() {
			var blue_box:Shape = new Shape();
			var red_box:Shape = new Shape();
			blue_box.graphics.lineStyle(1);
			blue_box.graphics.beginFill(0x0000FF, 1);
			blue_box.graphics.drawRect(200,150,100,100);
			red_box.graphics.lineStyle(1);
			red_box.graphics.beginFill(0xFF0000, 1);
			red_box.graphics.drawRect(220,170,100,100);
			addChild(blue_box);
			addChild(red_box);
		}
	}
}

This is the result: the red box is in front of the blue box because the red one was the last placed on the screen.

Understanding AS3 Shapes, Sprites and Depths

If you switch line 14 with line 15, the blue one will be the one on the top:

Understanding AS3 Shapes, Sprites and Depths

Sno now we know that the first child added with addChild() is placed at depth 0, the second one is placed at depth 1, and so on.

To know the depth value of an object, you can use getChildIndex(object_name);. So if you add this line:

trace(getChildIndex(red_box));

You will get a 1 in your output window.

To add an object at a specific depth position, you can use addChildAt(object_name, depth)

So let’s try this script:

package {
	import flash.display.Shape;
	import flash.display.Sprite;
	public class depths extends Sprite {
		public function depths() {
			var blue_box:Shape = new Shape();
			var red_box:Shape = new Shape();
			blue_box.graphics.lineStyle(1);
			blue_box.graphics.beginFill(0x0000FF, 1);
			blue_box.graphics.drawRect(200,150,100,100);
			red_box.graphics.lineStyle(1);
			red_box.graphics.beginFill(0xFF0000, 1);
			red_box.graphics.drawRect(220,170,100,100);
			addChild(blue_box);
			addChildAt(red_box,0);
		}
	}
}

Even if the red box was added after the blue box, it’s the blue one to stay on top because the red one was placed at depth zero.

Understanding AS3 Shapes, Sprites and Depths

That’s because if the specified depth is already taken by an existing object, then the new object is placed behind the existing one, whose depth is increased by one. So at the end of the script, the red box has depth zero, while the blue one has depth 1

You may ask: what if I change line 14 with

addChildAt(blue_box,1);

You can’t… you will get an error because as I said at the beginning of this post, you can’t leave “holes” in depth. So you can’t place an object at depth 1 if there isn’t an object at depth 0.

Using getChildIndex in a real life example, you can change line 15 with

addChildAt(red_box,getChildIndex(blue_box));

And you will get the same result.

Now, let’s see how to change depths dynamically.

package {
	import flash.display.Shape;
	import flash.display.Sprite;
	public class depths extends Sprite {
		public function depths() {
			var blue_box:Shape = new Shape();
			var red_box:Shape = new Shape();
			blue_box.graphics.lineStyle(1);
			blue_box.graphics.beginFill(0x0000FF, 1);
			blue_box.graphics.drawRect(200,150,100,100);
			red_box.graphics.lineStyle(1);
			red_box.graphics.beginFill(0xFF0000, 1);
			red_box.graphics.drawRect(220,170,100,100);
			addChild(blue_box);
			addChildAt(red_box,getChildIndex(blue_box));
			swapChildren(red_box,blue_box);
		}
	}
}

At line 16 the swapChildren method swaps red box’s depth with the blue box one. So we’ll have the red box in front again

Understanding AS3 Shapes, Sprites and Depths

Another way to change depths dynamically is changing line 16 with:

setChildIndex(blue_box,0);

Putting the blue box to depth zero again and make the red one stay on the top of the screen.

This was a brief introduction to AS3 depths. Obviously, more complex tutorials will come shortly.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers