ActionScript 3 Tutorial: Load New Object to Stage with Zero Depth
We learned from previous Flash ActionScript tutorial that an object loaded before another object will have a lower depth or position index. However we can change it. Even an object is added later, it can be placed at the bottom (zero depth). The secret is:addChildAt(Object_Name, 0)
Flash Tutorial Content:
Although an object load later to the stage will have a higher position index and thus appear in front of other objects with a lower position index, we can place an newly loaded object to the lowest position. This Flash ActionScript tutorial shows you how.
The complete Flash Movie is shown as above, you may try how it works before you start this tutorial.
Flash ActionScript Codes:
/*
Preparation: Create Linkage for the MovieClip
STEP 1: Prepare MovieClips
You already prepared three MovieClips in the library
In this example, the name of the MovieClips are:
- Tree
- Sun
STEP 2: Create Linkage
Select the movieclip from the library window
Select "Linkage..." from the pop up window
The Linkage Properties window appear
Check the "Export for ActionScript"
Enter Name in the Class field
In this example, we used "Tree" and "Sun" for the class name
*/
// Hide the reset button when movie starts
reset_btn.visible = false;
//Set the Apple RadioButton to be selected by default
tree_rb.selected = true;
//Declare the Radio group (belong to same group)
//This can be done by using the first RadioButton (apple_rb)
var myRadioGroup:Object = tree_rb.group;
// Create new MovieClips
var myMovieClip1:MovieClip = new Tree();
var myMovieClip2:MovieClip = new Sun();
// Set the location if required
myMovieClip1.x = 150;
myMovieClip1.y = 210;
// Set the location if required
myMovieClip2.x = 150;
myMovieClip2.y = 210;
enter_btn.addEventListener(MouseEvent.CLICK, addObjects);
function addObjects(evt:MouseEvent):void {
addChild(myMovieClip1);
// Add myMovieClip2 on the MainTimeline, and
// Put it to the depth zero
addChildAt(myMovieClip2, 0);
// Display message
output_txt.text = "Although Sun was added AFTER Tree, it was still placed BEHIND the Tree. Because the Sun was put to depth zero!";
// so that we can see it.
addChild(myMovieClip2);
addChild(myMovieClip1);
// Display message
output_txt.text = "Sun was in front of the Tree. Because Sun was added BEFORE Tree.";
enter_btn.visible = false;
// Show Reset button
reset_btn.visible = true;
}
reset_btn.addEventListener(MouseEvent.CLICK, clearObjects);
function clearObjects(evt:MouseEvent):void {
this.removeChild(myMovieClip1);
this.removeChild(myMovieClip2);
// Hide the Reset button
reset_btn.visible = false;
// Show the Enter button
enter_btn.visible = true;
}
Download Flash Source File:
Remarks:
This Flash ActionScript tutorial show how to load object to the lowest position. Even though objects had been added to the stage. Their position index can still be changed by using ActionScript. Please read next tutorial.