Javascript 游戏碰撞检测

Javascript game collision detection

我意识到这可能是一个常见问题,但在查看其他答案后,我不确定我的实施是否能从这些答案中获益。

我的游戏让玩家从其 X Y 位置向鼠标 X Y 位置射击,敌人沿 Y 轴直线下落。

不过,似乎只有第一枪或屏幕上的随机射击有时会击中并移除敌人,有些子弹会直接穿过并直接命中,而不会调用移除敌人。

游戏可以在这里看到: https://liammorgan.github.io/wave_defence/

命中检测的代码片段在这里,大约有 20% 的时间或在第一次子弹射击时起作用。

每次射击都有 X、Y、bulletSpeed、xVelocity、yVelocity

每个敌人都有一个 X、Y、速度

shot.js -
this.hit = function() {
        for(enemy in enemies) {
            let e = enemies[enemy];
            if(e != null) {             
                if(this.x+this.size > e.x && this.x-this.size < e.x && 
                this.y+this.size > e.y && this.y-this.size < e.y) {
                    enemies[enemy] = null;
                    return true;                    
                } else {
                    return false;
                }
            }
        }
    }

sketch.js -
let shots = [];
let enemies = [];
if(player.lives > 0) {
        player.update();
        player.draw();
        for(shot in shots) {
            let s = shots[shot];
            if(s != null) {                
                if(s.hit() && s != null) {
                    shots[shot] = null;
                    continue;
                }
                shots[shot].update();
                shots[shot].draw();
                if(s.remove() && s != null) {
                    shots[shot] = null;
                }
            }
        }
    }

在我看来,在你的碰撞逻辑中,你没有考虑敌人本身的大小。所以要计算碰撞次数,射击必须几乎完全击中敌人的正中心。

更好的方法是测量从子弹中心到敌人中心的距离,并检查其已知大小,因为敌人和子弹都是圆形。这也意味着您必须在敌人对象中包含一个 radiussize 字段。