我目前正在使用 canvas (JavaScript) 制作一个自上而下的射击 HTML5 游戏,这是我的问题:
当我射击时,函数会检查是否与敌人发生碰撞,如果是,它会摧毁敌人和子弹,但有时(随机)游戏会发生碰撞并返回错误:
uncaught TypeError: Cannot read property 'x' of undefined
at collides (game.js:274)
at checkBulletHits (game.js:177)
at Game (game.js:346)
在此错误中,“未定义”是我射出的最后一颗子弹,但这次子弹是未定义
,原因我不明白。
下面是涉及的代码:
var bullets = [];
var enemies = [];
function checkBulletHits() {
if (bullets.length > 0 && enemies.length > 0) {
for (j = bullets.length - 1; j >= 0; j--) {
for (k = enemies.length - 1; k >= 0; k--) {
if (collides(enemies[k], bullets[j])) {
enemies.splice(k, 1);
bullets.splice(j, 1);
player.points += 10;
}
}
}
}
}
function collides(a, b) {
return a.x < b.x + b.w &&
a.x + a.w > b.x &&
a.y < b.y + b.h &&
a.y + a.h > b.y;
}
checkBulletHits();
最佳答案
当发生碰撞时,您可以移除索引j
处的子弹。然后循环继续到下一个敌人,并在索引 j
处再次检查子弹。
该子弹不再存在,因此您正在调用collides(enemy, undefined)
。
然后,在collides
中,这显然会抛出一个错误:undefined.x
。
当你命中时,跳出循环。在 if
block 末尾添加 return
语句。
关于javascript - 错误 undefined object (尽管已定义),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47415711/