您可以按照您的描述进行操作,但我不建议您这样做。为此,您可以收听Event.REMOVED_FROM_STAGE 并执行某种清理:
// in your AI class
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
function removedFromStage(e:Event):void {
// remove all the bullets
for each(var bullet:Bullet in _bullets){
stage.removeChild(bullet);
}
_bullets.length = 0;
}
但是,这种方法是不现实的(子弹会在飞行中消失,而不是像您期望的那样继续前进),而且它不是一个很好的设计。
更好的方法是将所有子弹存储在主游戏类中。 AI负责“发射”一颗子弹,然后主类处理子弹的行进、碰撞等。如果你这样分离你的逻辑,你就不会遇到像你遇到的那样更多的问题了。
有很多方法可以实现这样的设计,但这里有一个我用过很多次的简单示例:
您的主游戏类:
public class Main {
// a list of all enemies in the game
private var enemies:Vector.<Enemy> = new <Enemy>[];
// a list of all bullets in the game
private var bullets:Vector.<Bullet> = new <Bullet>[];
// adds a new enemy to the game
public function addEnemy():void {
var enemy:Enemy = new Enemy(this); // pass a reference to this Main class
enemies.push(enemy);
addChild(enemy);
}
// removes an enemy from the game
public function removeEnemy(enemy:Enemy):void {
enemies.splice(enemies.indexOf(enemy), 1);
removeChild(enemy);
}
// adds a new bullet to the game
public function addBullet():void {
var bullet:Bullet = new Bullet(this); // pass a reference to this Main class
bullets.push(bullet);
addChild(bullet);
}
// removes a bullet from the game
public function removeBullet(bullet:Bullet):void {
bullets.splice(bullets.indexOf(bullet), 1);
removeChild(bullet);
}
}
你的敌人等级:
public class Enemy {
// a reference to the Main class
public var main:Main;
public function Enemy(main:Main){
// store the reference to the Main class
this.main = main;
}
// to shoot a bullet, call the Main class
public function shoot():void {
main.addBullet();
}
// to kill the enemy, call the Main class
public function die():void {
main.removeEnemy(this);
}
}
你的 Bullet 类:
public class Bullet {
// a reference to the Main class
public var main:Main;
public function Bullet(main:Main){
// store the reference to the Main class
this.main = main;
}
// to remove the bullet when it hits something, call the Main class
public function collide():void {
main.removeBullet(this);
}
}
如您所见,Main 类负责添加和移除敌人和子弹,代码中的其他各个地方只是简单地回调 Main 类。这种分离将防止您遇到类似的问题,并且在未来更加灵活。