【问题标题】:Test the value of an array against hitTest object针对 hitTest 对象测试数组的值
【发布时间】:2012-08-02 20:53:11
【问题描述】:

好的,我的主类中有一个如下所示的数组:

objectArray:Array = [ ];

我有三个函数来创建不同的项目,例如硬币、敌人、心等。这些添加的项目中的每一个都被推送到objectArray。我正在尝试编写这个函数来测试我的子弹对这些对象中的任何一个:

private function checkCollisions() :void{
    var bullet:MovieClip;
    for (var j:int = 0; j < objectArray.length; j++){
        object = objectArray[j];
        for(var i:int = 0; i < bulletArray.length; i++){
            bullet = bulletArray[i];
            if (objectArray[j].hitTestPoint(bullet.x, bullet.y, true)) {
                container.removeChild(bullet);
                bulletArray.splice(i,1);

                if (objectArray[j] == Enemy[j]){
                    container.removeChild(objectArray[j]);
                    objectArray.splice(j,1);
                    trace("enemy hit");
                }
            }
        }
    }
}

问题出在这部分:

if (objectArray[j] == Enemy[j]){  \\problem
    container.removeChild(objectArray[j]);
    objectArray.splice(j,1);
    trace("enemy hit");
}

我一直在尝试找到一种方法来测试被击中的对象是否针对某个值(例如“敌人”)进行测试,以便我可以根据被击中的对象类型产生不同的结果。无论我尝试哪种测试组合,我似乎都无法让它响应。当我跟踪objectArray[j] 时,它会产生[object Enemy] 作为结果。是否有其他测试数组值的方法?

【问题讨论】:

    标签: actionscript-3 collision-detection hittest


    【解决方案1】:

    听起来您想测试objectArray[j] 中的对象是否为Enemy 对象。您可以使用is 运算符来做到这一点:

    if (objectArray[j] is Enemy)
    {
        container.removeChild(objectArray[j]);
        trace ("enemy hit");
    }
    

    编辑

    此外,您可能希望以相反的顺序迭代项目符号/对象数组,因为您可能会在迭代时从数组中删除条目。

    for (var j:int = objectArray.length -1; j >= 0; j--){
     // then do the same with the bullet array
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      • 2012-11-05
      • 1970-01-01
      • 2015-12-29
      • 1970-01-01
      • 2020-07-09
      相关资源
      最近更新 更多