views:

40

answers:

3

I'm building a game of which the interface is one of the first items to load on screen. Sound button, pause and all the bits -

During the game - all manor of things are dynamically added and removed to the stage. Therefore my interface goes behind my game scene.

How do I ensure the movieclip always stays on top?

Can I override the addChild of my Document Class and every time a new child is added, I restack the interface to the top?

+1  A: 

Look into addChildAt, it allows you to specify the index that the new object should be added too.

http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/DisplayObjectContainer.html#addChildAt%28%29

A good strategy is to keep all interface elements in one parent Sprite/MovieClip, and all game assets in another. (With the interface one on top)

Tyler Egeto
Nice one, I did look at and I could see how it worked, but I wasn't sure how it was put together.
Glycerine
+1 for the comment about keeping all interface elements in one parent Sprite/MovieClip". That is the correct way to approach it.
aaaidan
+1  A: 

You can use setChildIndex to rearrange objects that are already contained within a MovieClip or Sprite. For example, if you have an object called container, which contains a redBall, blueBall and many other ball objects, you can use the following to make sure redBall is behind everything else:

container.setChildIndex(redBall, 0);

Equally you can make sure that blueBall will be displayed infront of everything else using:

container.setChildIndex(blueBall, container.numChildren-1);

addChildAt will sort you out for adding children straight into their correct position, and setChildIndex will allow you to re-position objects already placed. Hope that helps.

debu

debu
Sweet. Thats uber helpful.
Glycerine
No problem, glad it helped :)
debu
A: 

With your guys suggestion I made this, apparently, if you addChild an object already on the screen, it's simply reindex'd to the top. Does this look ok?

private var topLevelChildrenArray:Array = [];

public function addTopLevelChild(child:DisplayObject):DisplayObject
{
    topLevelChildrenArray.push(child)
    return this.addChildAt( child, this.numChildren - 1 );  
}

override public function addChild(child:DisplayObject):DisplayObject
{
    this.addChildAt(child, this.numChildren);

    for each(var topChild:DisplayObject in topLevelChildrenArray)
    {
        super.addChild(topChild);
    }

    return child
}
Glycerine