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

时间:2014-01-24 23:28:42

标签: actionscript-3 flash flash-cs6

所以我有一个在数组中实例化的敌人列表,我在屏幕上显示它们。当他们被射击时,我希望被射击的敌人从屏幕上移除。 BTW敌人类与敌人movieClip有AS链接,与Bullet相同。我明白问题是它无法比较和删除,但我不知道如何解决它。基本上我很想知道如何删除存储在数组中的类文件的实例?

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

    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");
    }
        }
    }

我在输出窗口中继续收到此错误: TypeError:错误#1010:术语未定义且没有属性。     在sniper_fla :: MainTimeline / shoot()[sniper_fla.MainTimeline :: frame1:58]

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:1)

从该敌方阵列移除项目的更复杂但 更快的方法是使用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);
}

当您从中删除某些内容时,此方法无需重新索引整个数组,如果您不断删除并向敌人列表中添加项目,这将产生巨大的性能提升。这种认可的缺点是敌人名单不会保持排序,但我认为不需要对其进行排序。

答案 1 :(得分:0)

自从我使用AS3以来已经很长时间了

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

应该适用于删除

我不确定你得到的错误

答案 2 :(得分:0)

@RustyH是正确的:

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

但是,由于你是在一个带有常量评估的for循环(i&lt; 4)中进行的,你可以做得更快一些:

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