我想在javascript上制作一个小游戏。在底部左右移动有一个角色,并且有些敌人不断从顶部掉落(有点像太空入侵者)。问题是,我无法进行碰撞检测。即使没有发生碰撞,它也始终检测到碰撞。如果有人能指出我正确的方向,我将非常感激。
这是我的代码。
function Orbs() {
// super constructor
Elementos.call(this);
this.setName("Orbs");
this.orbes = new Array();
this.canContinue = true;
};
Orbs.prototype = Object.create( Elementos.prototype );
Orbs.prototype.setData = function (stageRef, coorX, coorY) {
Elementos.prototype.setData.call(this, stageRef, coorX, coorY, "Orbs");
}
Orbs.prototype.toString = function() {
return "[Orbs] lab:";
}
Orbs.prototype.criar = function() {
var o = document.createElement('div');
o.id = "Orbes";
o.currentX = Math.random() * window.innerWidth;
o.currentY = 20;
o.speedX = 0;
o.speedY = 4;
o.size = 18;
this.orbes.push(o);
document.body.appendChild(o);
}
Orbs.prototype.movimento = function() {
this.lixo = new Array();
for (var i=0; i < this.orbes.length; i++) {
this.orbes[i].currentX += this.orbes[i].speedX = 0;
this.orbes[i].currentY += this.orbes[i].speedY;
this.orbes[i].style.left = this.orbes[i].currentX + "pt";
this.orbes[i].style.top = this.orbes[i].currentY + "pt";
if (this.orbes[i].currentY > 650) {
this.lixo.push(this.orbes[i]);
}
}
for (var i=0; i < this.lixo.length; i++) {
var index = this.orbes.indexOf(this.lixo[i]);
this.orbes.splice(this.index , 1);
document.body.removeChild(this.lixo[i]);
}
}
Orbs.prototype.colisao = function() {
for (var j=0; j < this.orbes.length; j++) {
if (this.isCollision(this.orbes[j]) == true) {
this.canContinue = false;
console.log("Hello");
setTimeout(this.endGame, 1000);
return;
}
}
}
var xix = Corpo.currentX;
var yips = Corpo.currentY;
var tamanh = Corpo.size;
Orbs.prototype.isCollision = function(var2) {
if ((xix > var2.currentX + var2.size - 1)
|| (yips > var2.currentX + var2.size - 1)
|| (var2.currentX > xix + tamanh - 1)
|| (var2.currentY > yips + tamanh - 1)) {
// no collision
return false;
}
// collision
return true;
}
Orbs.prototype.endGame = function() {
alert("Game Over");
}
Orbs.prototype.doAnimate = function() {
this.movimento();
this.colisao();
}
在我的第一次尝试中,我没有使用&#39; xix&#39; &#39;犬吠&#39;和&#39; tamanh&#39;变量,我像输入var一样输入它们,它只是报告它无法读取undefined的值。我怀疑这是因为我使用原型而产生的问题,但我无法确定。
任何帮助都将不胜感激。