PDA

View Full Version : Remove Array Elements from stage



snobdr8
July 30th, 2008, 04:50 PM
Hey Guys and Gals. I have the following code that duplicates a movie clip on my stage. At the end of my web banner I am having trouble making the movie clips disappear. It's an online banner so when the banner loops I don't want the duplicated clips to stay on the stage I just want them to clear off and have it start from scratch again. I've tried popping them through a function and the removeChild statement. Just stuck at the moment. Thanks!

//This array will hold all the rectangles on the stage
var rectangles:Array = new Array();


//In this loop, we'll create 50 rectangles
for (var i = 0; i < 25; i++) {

//Create one rectangle
var rectangle:Rectangle = new Rectangle();

//Assign a random position
rectangle.x = 15;
rectangle.y = 85;

//Add the rectangle on to the stage
addChild (rectangle);

//Add the rectangle to the array
rectangles.push (rectangle);

}

//The timer will call the "shakeRectangles" function every 0.02 seconds
var timer:Timer = new Timer(20, 100000000);
timer.addEventListener (TimerEvent.TIMER, shakeRectangles);
timer.start ();

//This function is responsible for animating the shake
function shakeRectangles (e:Event):void {

//Loop through the array
for (var i = 0; i < 25; i++) {

//Rotate the rectangle a random amount (from -4 to 4)
rectangles[i].rotation += Math.random() * 1 - 0.5;

//Assign a new random position
rectangles[i].x += Math.random() * 2 - 1;
rectangles[i].y += Math.random() * 2 - 1;
}
}

sekasi
July 30th, 2008, 06:32 PM
The code implies all the 'rectangles' are collected in the array 'rectangles' (btw you might want to look into code clarity and variable naming conventions xP). So,



function removeRectangles(source:Array):void {
var len:int = source.length;
for (var i:int = 0; i < len; i++) {
removeChild(source[i]);
};
source = null;
};

removeRectangles(rectangles);

snobdr8
July 30th, 2008, 06:38 PM
Sekasi - Much appreciated .. worked great! I did get a bit wacked out with the naming convention. I'll clean it up before I finalize the project :P. If you have any suggestions I'd be open to any due to the fact that I've just started getting into AS3. Thanks again.

sekasi
July 30th, 2008, 06:44 PM
Well, avoiding code on the timeline and moving to the document class is always a big :thumb2:

Don't forget to cast your variables as well.. makes a huge difference (var i:int = 0 ...) etc..