2017-04-20 4 views
-2

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は私が与えた状態を無視しているのですか?

+0

オブジェクトの中心の座標を追跡する '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)に '+'を使用する必要があります。 –

+0

ありがとう、しかしまだゴーストの衝突をもたらす – C12

答えて

0

2つのオブジェクトが重なってかどうかをテストするには

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; 
} 

を試してみてください。オブジェクトがx、yを左上、w、hを幅と高さとする場合

//Returns true if any part of box1 touches box2 
function areaTouching(box1,box2){ 
    return ! (box1.x > box2.x + box2.w || 
       box1.x + box1.w < box2.x || 
       box1.y > box2.y + box2.h || 
       box1.y + box1.h < box2.y) 
} 
+0

ありがとう、しかし、オブジェクトがオブジェクトの正確なxスポットにある場合のみ考慮し、オブジェクトの任意の部分が触れると発生する必要があります。 – C12

+0

@ C12テストの例を追加しましたifボックスが重なり合う – Blindman67

関連する問題