2015-04-04 43 views
0

我的2D遊戲中碰撞檢測有問題。對象的頂部和左側碰撞良好,但在對象的底部和右側不能按預期工作。我該如何解決它?

的Javascript:使用JavaScript和HTML5 canvas進行碰撞檢測

this.isPlayerCollideWith = function(object) { 

    if (this.posX < objekt.posX + object.width && this.posX + this.width > object.posX && 
     this.posY < object.posY + object.height && this.posY + this.height > object.posY) { 

     //up 
     if(this.posY < objekt.posY + object.height){ 
      this.posY -= this.speed; 
     } 
     //down 
     if(this.posY + this.height > object.posY){ 
      this.posY += this.speed; 
     } 

     //left 
     if(this.posX < object.posX + object.width){ 
      this.posX -= this.speed; 
     } 

     //right 
     if(this.posX + this.width > object.posX){ 
      this.posX += this.speed; 
     } 

    } 
}; 

我所有的代碼是通過HTML5畫布上運行。

回答

0

你有一個錯字:objekt應該是object

你碰撞的邏輯可能(也可能不是)也關閉。這裏的工作代碼:

if(!(
    this.x    > object.x+object.width || 
    this.x+this.width < object.x   || 
    this.y    > object.y+object.height || 
    this.y+this.height < object.y 
)){ ... }