碰撞检查循环在敌人产生后停止循环

时间:2017-02-19 11:24:18

标签: javascript for-loop collision-detection

所以我一直用javascript制作这个小射击游戏,我遇到了一个我无法弄清楚的问题。

我有一个碰撞检查,检查是否有任何活着的敌人与玩家或使用for循环的子弹发生碰撞。循环运行良好,直到我产生一个敌人。

在for循环的开头你可以看到console.log,它只记录数字直到第一个活着的敌人index。例如,如果enemies[4]还活着,并且之前没有其他index的敌人还活着,则会一直记录0, 1, 2, 34。如果我然后杀死所有敌人,那么循环将再次运行50次(这是阵列的长度),直到敌人产生。

checkCollision: function(){
    function calculate(enemy, other){
        var r = enemy.r + other.r;
        var dx = enemy.posX - other.posX;
        var dy = enemy.posY - other.posY;
        var d = Math.sqrt((dx * dx) + (dy * dy));
        if(r > d){
            enemy.alive = false;
            other.alive = false;
            return true;
            }
        return false;­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
    }
    for (var i = 0, max = this.enemies.length; i < max; i++) {
        console.log(i);
        if(this.e­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­nemies[i].alive){
            if(calculate(this.enemies[i], this.player)){
                continue;
            }
            for (var i = 0, max = this.player.weapon.bullets.length; i < max; i++){
                if(this.player.weapon.bullets[i].alive){
                    if(calculate(this.enemies[i], this.player.weapon.bullets[i])){
                        break;­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
                    }
                }­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
            }
        }
    }    ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
}

这是一个小小的可视化:

[0] = !alive
[1] = alive
[2] = !alive
[3] = alive
[4] = alive

现在for循环只运行2次,因此没有检查3和4的碰撞,这就是我想要的。

1 个答案:

答案 0 :(得分:1)

嗯,你有一个循环,循环遍及所有敌人,但一次只检查一个敌人,只检查player,而不是相互对抗。

所以尝试类似:

    for (var i = 0, max = this.enemies.length; i < max; i++) {
        for (var j = 0, max = this.enemies.length; j < max; j++) {
            if(calculate(this.enemies[i], this.enemies[j]){
                doSomething();
            }
        }
    }
    // Don't forget the player.

如果你感兴趣的话,有一个非常好的HTML5 Game Development课程教你如何使用开源物理引擎来处理这些事情。

在寻找工作的同时,我使用该开源项目制作了一个小版本的Mario,以及该课程的信息。您可以在“项目”下的my website上看到游戏。

修改

所以在你的例子后我理解你的问题。您正在内循环中重用关于项目符号的imax变量。因此,如果内部循环结束,外部循环也将终止,因为它们都检查i < max