我正在用HTML写一个版本的太空入侵者,激光和敌人之间的碰撞检测不起作用。我没有在开发者控制台中看到任何错误。
// Returns whether or not an object is empty, i.e., does not exist.
function isEmpty(obj) {
for(var key in obj) {
if(obj.hasOwnProperty(key))
return false;
}
return true;
}
function laserCollision() {
for(var i = enemyArray.length - 1; i >= 0; i--) {
for(var j = playerLaserBeamsArray.length-1; j >= 0; j--) {
// make sure not to access an object which does not exist.
if(isEmpty(playerLaserBeamsArray[j])) break;
if(isEmpty(enemyArray[i])) break;
// check if laser beam is at correct y coordinate
if(playerLaserBeamsArray[j].getTopY() >= enemyArray[i].getBottomY() && playerLaserBeamsArray[j].getBottomY() <= enemyArray[i].getTopY()) {
// check if laser beam is between the enemy's furthermost left and right x-coordinates
if(playerLaserBeamsArray[j].getLeftX() <= enemyArray[i].getLeftX() && playerLaserBeamsArray[j].getRightX() <= enemyArray[i].getRightX()){
score ++;
enemyArray.splice(i, 1);
}
}
}
}
}
enemyArray是敌人对象的数组,playerLaserBeamArray是一个激光束对象数组。敌人是三角形,激光束是矩形。 两个对象都有getLeft()和getRight()方法返回左右角,getTopY()和getBottomY()返回最远的y坐标。
github回购是: https://github.com/Ruben-Krueger/Interstellar-Invaders
可以在以下位置播放: https://ruben-krueger.github.io/Interstellar-Invaders/