Macromedia Flash MX 2004 ActionScript Programming Tutorial

Removing Duplicated Movie Clips

When you duplicate a movie clip using the duplicateMovieClip method of the MovieClip object, you have to remove the duplicate clips using the removeMovieClip method. Even though our asteroids disappear when they encounter the ship’s windshield, the movie clips still exist—they’re just invisible. While they exist, they gobble system resources unnecessarily. We can add a do…while loop to the end of our makeAsteroid() function to remove the duplicates once they’ve disappeared.

Following is the code comprising our makeAsteroid() function, with our loop to remove the movie clips added inside the if statement at the end:

function makeAsteroid() {

//increment our movie clip counter

num_clips++;

//duplicate our movie clip

asteroid_mc.duplicateMovieClip(“asteroid_mc” + num_clips, num_clips);

//position our new copy of the movie clip

_root[“asteroid_mc” + num_clips]._x = Math.random() * 550;

_root[“asteroid_mc” + num_clips]._y = 1;

if (num_clips == 10) {

clearInterval(asteroidInterval);

//remove our movie clips starting with the first duplicate

var dupAsteroid = 1;

do {

//remove a movie clip

_root[“asteroid_mc” + dupAsteroid].removeMovieClip();

//decrement num_clips counter

num_clips–;

//increment our remove movie clip counter

dupAsteroid++;

} while (dupAsteroid <= 10);

}

}

We placed the loop inside the if statement so that it only executes when the number of asteroids (num_clips) reaches 10. It would have been simpler to use our num_clips counter to remove the asteroids and decrement the counter back down to 1, but if we’d done this, we wouldn’t have seen the tenth asteroid appear, since it would have been removed as soon as it was duplicated. It was better to remove the clips starting with the first duplicate (named “asteroid_mc1”). To do this, we just created another counter (the dupAsteroid variable) and incremented it. When the loop finishes, all the duplicates will be removed from the movie, leaving the original movie clip invisible on the stage.

One Comment

  1. zoe

Leave a Reply

Your email address will not be published. Required fields are marked *