我意识到这可能是一个常见问题,但在查看其他答案后,我不确定我的实现是否能从这些答案中获益。
我的游戏让玩家从其 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;
}
}
}
}
最佳答案
在我看来,在您的碰撞逻辑中,您没有考虑敌人本身的大小。因此,要计算碰撞次数,射击必须几乎完全击中敌人的正中心。
更好的方法是测量从子弹中心到敌人中心的距离,并检查其已知大小,因为敌人和子弹都是圆形。这也意味着您必须在敌人对象中包含一个 radius
或 size
字段。
关于Javascript 游戏碰撞检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54094469/