Reputation: 35
OK, so I have a laser gun and it is shooting lasers (well duh) called laser_mc and I am putting in the enemies now. There is one problem though. When I add the enemies named bad
they get added, removed and then reappear somewhere else.
Here is my code. What did I do wrong?
var badadd:bad; badadd = new bad()
addEventListener(Event.ENTER_FRAME, createbad);
function createbad(event:Event):void {
addChild(badadd);
badadd.x = Math.random()*stage.width;
badadd.y= Math.random()*stage.height;
}
addEventListener(Event.ENTER_FRAME, removebad);
function removebad(event:Event):void {
if (laser_mc.hitTestObject(badadd)) {
removeChild(badadd);
}
}
Upvotes: 0
Views: 279
Reputation: 11
They get removed and placed elsewhere because you are using an enter_frame loop here. Every single time a frame ticks off your program adds the same enemy at a random location. So it adds at a random place, removes it, then adds it at a random place all over again.
You might want to try something like this:
Set up a for loop and fill an array with enemies. Declare the array as a class property\, EnemyArray. Like (pseudocode):
for i = 1 to 10
var tempEnemy = new Enemy()
EnemyArray[i].push(tempEnemy) // put the enemy in the array
Now when you need to add an enemy - it's already been instantiate so you just need to go:
addChild(tempEnemy[index]);
Now you can cycle through the array for hit testing, etc.
Let me know if this is too conceptual and I'll write the code out a bit more.
Upvotes: 1