the code below simply creates a timer that fires 20 times…
everytime the timer fires, it runs a function that:
1.) adds a movieclip on stage…
2.) adds the movieclip / to an array called enemyArray
once on stage, the movieclip creates a timer, which, when fired, will run a function that will remove itself from the stage…
an enterframe event is also created, which simply updates a textfield on stage and makes it display the current length of enemyArray…
MY PROBLEM IS… how do i tell flash to remove the movieclip (or movieclip reference, not really sure how to call it) from the enemyArray after it removes itself from stage?
on the main timeline:
var enemyArray:Array = new Array();
var timeToCreateEnemy:Timer;
// set up timer that will fire every 2 seconds, 20 times
timeToCreateEnemy = new Timer(2000, 20)
timeToCreateEnemy.addEventListener(TimerEvent.TIMER, createEnemy);
timeToCreateEnemy.start();
addEventListener(Event.ENTER_FRAME, frameEntered);
// function that will create an enemy when timer fires
function createEnemy(event:TimerEvent):void
{
var enemyShip:MovieClip = new Enemy();
enemyArray.push(enemyShip); // put this enemy into the array
enemyShip.x = Math.round(Math.random() * stage.stageWidth);
enemyShip.y = Math.round(Math.random() * stage.stageHeight);
addChild(enemyShip);
}
// update textfield on how many items are in the array
function frameEntered(event:Event):void
{
theText.text = String(enemyArray.length);
}
inside the Enemy class:
package
{
import flash.display.*;
import flash.events.*;
import flash.utils.Timer;
public class Enemy extends MovieClip
{
var timeToRemoveMe:Timer;
public function Enemy()
{
initEnemy();
}
/*set up a timer that will fire once after a random number
of seconds ranging from 1 to 10*/
function initEnemy():void
{
timeToRemoveMe = new Timer(Math.ceil(Math.random() * 10000), 1);
timeToRemoveMe.addEventListener(TimerEvent.TIMER, removeMe);
timeToRemoveMe.start();
}
// removes enemy from stage
function removeMe(event:TimerEvent):void
{
timeToRemoveMe.removeEventListener(TimerEvent.TIMER, removeMe);
MovieClip(root).removeChild(this);
/*IMPORTANT PART... need to put some sort of code here that will also remove
this item from the "enemyArray" Array on stage*/
}
}
}