Saturday, August 22, 2009

Controlling the Stacking Order in Flash


Sometimes you may want to dynamically change the stacking order (The order that determines which objects are in front of each other on the stage).

In AS3.0 you would use the addChildAt() method.

1: This is an example of the AS3.0 solution. In this code example there are four MovieClips on the stage (box01_mc - box04_mc).

2: Each MovieClip has two event listeners assigned to it. The first listener is triggered on the RollOver (called MOUSE_OVER in AS3.0) and runs the function called enlargeMC. The second listener listens for the RollOut (called MOUSE_OUT in AS3.0) and triggers a function called shrinkMC.

3: The enlargeMC function contains code for making the movieClip that is rolled over enlarge (notice that in AS3.0 the scale value uses the values 0-1, with .5 here being a 50% increase in size)

4: In addition to the code that changes the scale property, an addChildAt method is used to move whichever movieClip is rolled over to the top of the display stack.


box01_mc.addEventListener(MouseEvent.MOUSE_OVER, enlargeMC);
box01_mc.addEventListener(MouseEvent.MOUSE_OUT, shrinkMC);
box02_mc.addEventListener(MouseEvent.MOUSE_OVER, enlargeMC);
box02_mc.addEventListener(MouseEvent.MOUSE_OUT, shrinkMC);
box03_mc.addEventListener(MouseEvent.MOUSE_OVER, enlargeMC);
box03_mc.addEventListener(MouseEvent.MOUSE_OUT, shrinkMC);
box04_mc.addEventListener(MouseEvent.MOUSE_OVER, enlargeMC);
box04_mc.addEventListener(MouseEvent.MOUSE_OUT, shrinkMC);



function enlargeMC(myEvent:MouseEvent):void {
myEvent.target.scaleX += .5;
myEvent.target.scaleY += .5;
addChildAt(DisplayObject(myEvent.target), numChildren-1);
}


function shrinkMC(myEvent:MouseEvent):void {
myEvent.target.scaleX -= .5;
myEvent.target.scaleY -= .5;
}



No comments:

Post a Comment