如何删除数组 AS3 中的类实例



所以我有一个数组中实例化的敌人列表,我把它们放在屏幕上。当他们被击中时,我希望被击中的敌人从屏幕上移除。顺便说一句,敌人职业与敌人电影剪辑有AS链接,子弹也是如此。我知道问题是它无法比较和删除,但我不知道如何解决它。基本上我很想知道如何删除存储在数组中的类文件的实例?

这是我到目前为止得到的:

stage.addEventListener(MouseEvent.CLICK, shoot);
var enemyList:Array = new Array();
addEnemies(608.75, 371.85);
function addEnemies(xLoc:Number, yLoc:Number):void {    
var enemy:Enemy = new Enemy(xLoc, yLoc);
addChild(enemy);
enemyList.push(enemy);
}
function shoot(event:MouseEvent):void{
for(var i:int = 0; i < 4; i++){
var enemy:Enemy = enemyList[i];
if(scope.redDot.hitTestObject(enemy)){
trace("SHOT TO DEATH");
}
else{
trace("DIDNT DIE");
}
}
}

我在输出窗口中不断收到此错误: 类型错误: 错误 #1010: 术语未定义且没有属性。 at sniper_fla::MainTimeline/shoot()[sniper_fla.主时间轴::帧1:58]

任何帮助将不胜感激!

从该敌人数组中删除物品的一种更复杂但更快的方法是使用pop()

function removeEnemy(enemy:Enemy):void
{
var i:int = enemyList.indexOf(enemy);
if(i >= 0)
{
if(enemyList.length === 1 || enemyList[enemyList.length] === enemy)
{
// If we are referring to the last enemy in the list, or there is only
// one enemy in the list, we can just use pop to get rid of the target.
enemyList.pop();
}
else
{
// In this case, we remove the last enemy from the array and retain a
// reference to it, then replace the target enemy we want to remove
// with that enemy.
var tempEnemy:Enemy = enemyList.pop();
enemyList[i] = tempEnemy;
}
}
// We can also remove the Enemy from the stage in this function.
enemy.parent && enemy.parent.removeChild(enemy);
}

这种方法消除了在从中删除某些内容时重新索引整个阵列的需要,如果您不断删除项目并将其添加到敌人列表中,这将产生巨大的性能改进。这种方式的缺点是敌人列表不会保持排序,尽管我认为没有必要对其进行排序。

自从我使用 AS3 以来已经有很长时间了,但是

enemyList.splice(enemyList.indexOf(enemy), 1)

应该为移除工作

我不确定您遇到的错误

@RustyH是正确的:

enemyList.splice( enemyList.indexOf( enemy ), 1 );

但是由于您是在具有恒定评估(i <4)的 for 循环中执行此操作,因此您可以这样做,速度稍快:

enemyList.splice( i, 1 );

还有您得到的空引用错误:

TypeError: Error #1010: A term is undefined and has no properties. at sniper_fla::MainTimeline/shoot()[sniper_fla.MainTimeline::frame1:58]

这很可能是由您的原因引起的:scope.redDot.hitTestObject(enemy)尤其是scope或儿童scope.redDot。当您尝试引用它时,其中之一可能不存在。您必须彻底检查您的代码,但这是在时间轴中编码的缺点,因为它可能是许多不同的问题(或根本没有以下问题),例如:

  • redDot不作为作用域的子项存在
  • 尚未在当前帧上创建redDotscope(或两者)
  • 引用名称不正确scoperedDot

这个列表还在继续...同样,这都是猜测错误是scopescope.redDot.

最新更新