O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Moving Objects Forward and Backward

Problem

You want to change the order in which objects are drawn on-screen, moving them either in front of or behind other display objects.

Solution

Use the setChildIndex() method of the DisplayObectContainer class to change the position of a particular item. Use the getChildIndex() and getChildAt() methods to query siblings of the item so the item can be positioned properly relative to them.

Discussion

Recipes 6.1 and 6.2 introduced how the display list model deals with the visual stacking order (depth). Essentially, every DisplayObjectContainer instance has a list of children, and the order of the children in this list determines the order in which child display objects are drawn inside of the container. The children are each given a position index, ranging from 0 to numChildren – 1, much like an array. The child at position 0 is drawn on the bottom, underneath the child at position 1, etc. There are no empty position values in the list; if there are three children, the children will always have index values of 0, 1, and 2 (and not, say, 0, 1, and 6).

The setChildIndex() method is provided by DisplayObjectContainer to reorder the children inside the container. It takes two parameters: a reference to the child to be moved and the child’s new position in the container. The index position specified must be a valid value. Negative values or values too large will generate a RangeError and the function won’t execute properly.

The following example creates ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required