Example 1: Creating and Deleting Display Objects. 'getChildAt' method.

Creating, deleting and manipulating a non-predetermined number of display objects at runtime in Flash CS3 is a frequently encountered issue when programming highly interactive applications, for example games or math applets. The approach to such issues is dramatically different in AS3 from the way it was in AS2. In this tutorial, we look at two examples, first a simpler one. (It will be easier for you to follow this tutorial after you look at the preceeding Depths Management in Flash CS and AS3 tutorial.)

Download

Download the fla file for this example with complete, well-commented source code.

The Challenges in Example 1

As you can see in the above applet, the user can create and delete any number of dots on the graphing board, in no particluar order. Any time a dot is added or deleted, the applet updates the fill which is obtained by joining those dots that remain on the board in the order that they were added. The issues (besides creating listeners that add, delete, and draw dots) are:

  • Keeping track of the number and order of dots remaining on the board.
  • Accessing the dots in the correct order to draw the desired fill.

Beacause of AS3 Display List model and its depths management model, those challenges are surprisingly easy to meet. The dots are automatically kept in the right order as children of a Sprite, spDotHolder, that serves as the dots' container. We access them by simple:

spDotHolder.getChildAt(i);

(The index i varies from 0 to spDotHolder.numChildren-1.)

One must note, however, that much casting is needed to avoid compiler errors in Strict Mode.

We discuss the code in more detail on page 3 of this tutorial.

On the next page, we show a more complex example in which the method getChildAt does not suffice. We need to use the new to AS3 property of display objects: DisplayObject.name and the getChildByName method.

Back to Intermediate Tutorials              Back to Flash and Math Home

We welcome your comments, suggestions, and contributions. Click the Contact Us link below and email one of us.

Adobe®, Flash®, ActionScript®, Flex® are registered trademarks of Adobe Systems Incorporated.