This is an update to the example we did in class about adding MovieClips from the library and removing them from the stage. After the class I realized there was an easier way to write this that acutally used less AS3.  The AS3 used for this example is below it along with the source files for download.

Get Adobe Flash player

          //makesure you have a MovieClip in the Library exported for ActionScript with the class: Star
          //create a new variable and datatype it as a Star (the MovieClip you have in the library)
var newStar:Star;
 
          //add a mouseDown listener to the stage that will call the function addRemoveStar
stage.addEventListener(MouseEvent.MOUSE_DOWN, addRemoveStar);
             //BestPractice (no stage / weak reference):    this.addEventListener(MouseEvent.MOUSE_DOWN, addRemoveStar, false, 0, true);  
 
          //write the function addRemoveStar
function addRemoveStar(e:MouseEvent)
              //BestPractice(return void):     function addRemoveStar(e:MouseEvent):void
{
 
	       //create a variable named objectClicked and store the target of the MouseDown Event
	       //(it will either be the stage or something that has been added to the stage like a newStar)
	var objectClicked = e.target;
 
	       //create an if statement to find out if the target of the mouseDown event was the stage or a newStar
	if(objectClicked == stage)
	{
		       //when the target of the mouseDown event is the stage, create a new instance of the Star called newStar
		newStar= new Star;
 
		       //position the newStar at the x and y coordinates of the mouse
		newStar.x = mouseX;
		newStar.y = mouseY;
 
		       //add the newStar to the stage
		stage.addChild(newStar);
	}
	       //when the target of the mouseDown event is not the stage it means it is a newStar
	else
	{
		          //remove the newStar that was clicked (the target of the mouseDown event)
		stage.removeChild(objectClicked);
	}
}

Download starClick Source Files

Number of Downloads: 34

Download Size: 6.3 kB

Download Updated: March 21, 2009

Tags: ,