AS3 layer order

Kris picture Kris · Oct 23, 2011 · Viewed 7.2k times · Source

I created two empty Sprites to serve as layers, bottom_spr and top_spr

When clicking a button, a MovieClip appears and follows your mouse, untill you click, then its position is fixed.

As soon as the button is clicked, I addChild the MovieClip to the correct Sprite.

Unfortunately, the layer system doesn't see to work, because they are layered in the order I place them, the Sprites don't seem to influence it.

How is this possible?

private var ground_spr:Sprite;
private var units_spr:Sprite;

public function Game() {
addEventListeners();

ground_spr = new Sprite();
units_spr= new Sprite();

addChild(ground_spr);
addChild(units_spr);
}

private function addEventListeners(){
groundBtn.addEventListener(MouseEvent.CLICK, clickGroundBtn);
unitBtn.addEventListener(MouseEvent.CLICK, clickUnitBtn);
}

private function clickGroundBtn(event:MouseEvent){
    var ground = new Ground_mc();
follow();
ground_spr.addChild(ground);
}

private function clickUnitBtn(event:MouseEvent){
    var unit = new Unit_mc();
follow();
units_spr.addChild(unit);
}

Answer

Austin Henley picture Austin Henley · Oct 23, 2011

Your question is very vague but I will attempt to answer it. If you clarify how you want your objects ordered exactly, I can better answer your question. It is fine to add layer of abstraction over the depth handling, if you need it. In this case I dont see much of a need, but I will show you a few things you could do.

To add an object to the back of the screen:

this.setChildIndex(objName, 0);

To add an object to the front of the screen:

this.setChildIndex(objName, this.numChildren - 1);

To swap the depths of two objects:

this.swapChildren(objA, objB);
//Note this is expecting two DisplayObjects so you may have to do:
this.swapChildren(objA as DisplayObject, objB as DisplayObject);