When two objects overlap eachother, one of them is going to be on top. The first object added to the stage has an index of 0. If you add another object (for example, using the addChild() method) it will have an index of 1, and so on.

There can't be any 'holes' in these depths, for example, if you only have 2 objects, their depths will be 0 and 1 no matter what. They can't be, for example, 0 and 10, if there are no objects to have a depth from 2 to 9.

Now let's talk about the setChildIndex and getChildIndex functions. Say, you have a bunch of movie clips on stage, and you want a MC with instance name of "sample" to go behind all the other objects. To do this, just set the object's depth to 0.

setChildIndex(sample,0);

What do we do, if we need to get that "sample" movieclip to front? We'll need to change his depth to the highest available. How do we find that out? Using numChildren! We take the number of all objects (numChildren) and deduct it by 1 (because the depths start from 0) to find the highest available depth. Think of it as of an Array, where all objects are listed, with the first object having an index of 0 and numChildren being the length property.

setChildIndex(sample,numChildren-1);

We can find out an object's depth using the getChildIndex function.

getChildIndex(sample);

What if we need to set a depth relative to something else?

setChildIndex(sample, getChildIndex(sample2));

This code sets sample's depth to sample2's previous depth, and moves sample2 1 depth up. To put sample in front of sample2:

setChildIndex(sample, getChildIndex(sample2)+1);

Method addChild() creates an object and places it on top of everything else (gives it the highest depth). You can manually set the child's depth using the addChildAt() function:

addChildAt(sample, 1);

That's pretty much it.

Thanks for reading!

## No comments:

## Post a Comment