Reverse display list objects in AS3

Some simple tricks must be included to reverse display list objects in AS3 and that trick uses name MovieClip property, getChildByName and swapChildrenAt methods. Let's see code first.

import flash.display.MovieClip;

var temp:MovieClip = new box();

for (var i:Number = 0; i < 50; i++) {
    temp.x = Math.random()*500;
    temp.y = Math.random()*350; = String(i);
    temp.alpha = i/50;
    temp = new box();

stage.addEventListener(MouseEvent.CLICK, onStageClick);
function onStageClick(evt:MouseEvent):void {
    for (var j:Number = 0; j < numChildren/2; j++) {
        swapChildrenAt(j, numChildren-j-1);
        getChildByName(String(j)).name = String(numChildren-j-1);
        getChildByName(String(numChildren-j-1)).name = String(j);
        getChildByName(String(j)).alpha = j/50;
        getChildByName(String(numChildren-j-1)).alpha = (numChildren-j-1)/50;        

For this example I will use MovieClip alpha property for visual representation of change after list reversing. First simple shape (sqaure in my case) has box class as linkage name.

Using for loop place on stage 50 of those boxes on random positions, but inside stage width and height dimensions. Using = String(i) line every box is named after its depth value, meaning first box added to stage will have name "0", second name "1", etc. Last one will have name "49".

Then, with temp.alpha = i/50 line we make every new box have slightly higher alpha value than previous one. We will reverse those alpha values later.

Function onStageClick will have single for loop, but with index going only half of number of boxes. In this way using swapChildrenAt we replace depth of box "0" with depth of box "49", depth of box "1" with depth of box "48", etc while entire list is reversed.

All that is left is to change names and alphas of new order using getChildByName method.

Image shows two different states, before and after the reverse.


Post a Comment