在javascript中,我制作了一个HTML画布游戏,在那个游戏中我有一个名为gamePiece的对象类型/构造函数。游戏币有一个功能叫做checkCollision:为什么我的情况不起作用?
this.checkCollision = function(piece){
var collisionX = piece.x >= this.x && piece.x <= (this.x + this.width);
var collisionY = piece.y <= this.y && piece.y <= (this.y - this.height);
if(collisionX || collisionY){
return true;
} else {
return false;
}
}
这是由更新称为()
function update(){
context.clearRect(0, 0, game.width, game.height);
for(var i = 0; i < gamePieces.length; i++){
gamePieces[i].update();
for(var mi = 0; mi < gamePieces.length; mi++){
gamePieces[i].checkCollision(gamePieces[mi]);
if(gamePieces[i].checkCollision(gamePieces[mi]) == true){
gamePieces[i].collisionFunction();
}
}
}
}
setInterval(function(){update();}, 1);
我有一个应该在与其他游戏人物碰撞给提升速度的另一个对象,它记录每次都会提高速度。
var speedBooster = new gamePiece(25,25,"red",300,300,0);
speedBooster.collisionFunction = function(){
for(var whichpiece = 0; whichpiece < gamePieces.length; whichpiece++){
if(speedBooster.checkCollision(gamePieces[whichpiece]) == true && gamePieces[whichpiece] != this){
gamePieces[whichpiece].speed += 10;
console.log("gamePieces[" + whichpiece + "] has been given a speed boost.");
}
}
}
但是它给出了一个速度提升,只要一块是它的背后,我把“piece.x> = this.x & &”有原因的。为什么JavaScript忽略了我给它的条件?
'x'和'y'是否跟踪物体中心的坐标?如果是这样,问题可能是你正在使用x和y的对象的全部宽度,分别在正面和负面方向,而不是集中在对象上。即是否会像这样工作? var collisionX = piece.x> =(this.x - this.width/2)&& piece.x <=(this.x + this.width/2); var collisionY = piece.y <=(this.y - this.height/2)&& piece.y <=(this.y + this.height/2); 另外,你应该在(this.y - this.height)中使用'+'。 –
谢谢,但仍然产生鬼碰撞 – C12