问题
the problem is when i shoot down my enemy he keeps re-spawning. probably something i overlooked.
i can shoot it, it gets removed from stage but gets rerenderd because it still exist in my array.
thanks
private function enemySpawnen():void
{
for(var i:uint = 0; i < hoeveelheidEnemy;i++){
var enemyShip:SpaceShip = new SpaceShip();
Enemy[i] = enemyShip;
}
}
private function renderEnemy(e:Event):void
{
for(var i:uint = 0; i < hoeveelheidEnemy;i++){
if(Enemy[i] != null){
viewContainer.addChild(Enemy[i]);
Enemy[i].scaleX = 0.5;
Enemy[i].scaleY = 0.5;
Enemy[i].x = 500;
Enemy[i].y = 400 - i*100;
}
}
}
function shoot(e:Event):void
{
kogel.x +=10;
try{
for(var i:uint = 0; i < hoeveelheidEnemy;i++){
if(kogel.hitTestObject(Enemy[i])){
Enemy.splice(i,0);==>problem when i set it to 1 or i then nothing happens
viewContainer.removeChild(Enemy[i]);
//trace("hit");
}
}
}
catch(e:Error){
}
}
My source code can be found here: http://dl.dropbox.com/u/50815831/Nieuwe%20map.zip
回答1:
You need to remove the child BEFORE you splice the array. You also need to iterate backwards so your indices don't change mid loop.
Try changing your for loop to the following:
for(var i:uint = Enemy.length-1; i >= 0;i--){
if(kogel.hitTestObject(Enemy[i])){
viewContainer.removeChild(Enemy[i]);
Enemy.splice(i,1); //do this after the above line, otherwise you're actually removing doing removeChild on the next item in the array
kogel.removeEventListener(Event.ENTER_FRAME, shoot); //stop the frame handler
break; //abandon the rest of this loop
}
}
If Kogel is a bullet and you want it to only affect one enemy, then you need to break out of the loop once it destroys something.
As a tip for good practice. you should encapsulate the shoot function/enter frame handler into your Kogel class and just pass in the enemy array.
Something else I've noticed, your have your renderEnemy function run every frame, which is completely uneccessary, and causing undesired positioning. Delete that function all together and put the code into your enemySpawned() method:
private function enemySpawnen():void
{
for(var i:uint = 0; i < hoeveelheidEnemy;i++){
var enemyShip:SpaceShip = new SpaceShip();
Enemy[i] = enemyShip;
viewContainer.addChild(Enemy[i]);
Enemy[i].scaleX = 0.5;
Enemy[i].scaleY = 0.5;
Enemy[i].x = 500;
Enemy[i].y = 400 - i*100;
}
}
来源:https://stackoverflow.com/questions/13314520/my-object-doesnt-get-removed-in-array