JavaScriptで、私はHTMLキャンバスゲームを作っています。そのゲームでは、gamePieceというオブジェクトタイプ/コンストラクタがあります。 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.");
}
}
}
しかし、作品はその背後にある、と私は理由のためにそこに「> = this.x & & piece.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