所以我创造了一个游戏,在游戏中,人工智能向玩家射击。这个问题是当AI发射一颗子弹,在子弹被摧毁之前被杀死,子弹在半空中结冰,因为AI被从舞台上移走。这里有一段视频展示了我的意思:http://i.gyazo.com/a13a43467ae8c6c3d8b1c988b7010bc2.mp4
ai的子弹存储在一个数组中,我想知道当ai本身从舞台上被移除时,是否有一种方法可以移除由ai添加到舞台上的孩子。
这是处理被玩家子弹击中的AI的代码。ai的子弹以相同的方式存储,但存储在另一个类/文件中。
for (var i = _bullets.length - 1; i >= 0; i--) {
for (var j = enemies.length - 1; j >= 0; j--) {
if (_bullets[i].hitTestObject(enemies[j])) {
stage.removeChild(enemies[j]); //removes the ai
stage.removeChild(_bullets[i]); //removes the players bullet
_bullets.splice(i, 1);
enemies.splice(j, 1);
return;
}
}
}
发布于 2015-01-23 21:10:37
你可以照你说的做,但我不建议你这么做。要做到这一点,您可以监听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);
}
}
你的子弹类:
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);
}
}
如您所见,主类负责添加和移除敌人和子弹,代码中的其他各种位置只需调用主类即可。这种分离将防止像您遇到的问题,并在今后的道路上更加灵活。
https://stackoverflow.com/questions/28118263
复制相似问题