2014-01-28 55 views
0

我想在我目前正在使用的JavaScript程序中進行碰撞檢測工作,但我無法弄清楚它爲什麼會在這種奇怪的座標中觸發。 X 50 Y 199JavaScript碰撞檢測不起作用

如果你們中的任何一位都能很好的幫助,那將會非常感謝。這是我的代碼。基於Y軸我說你的if語句

var game = {}; 
game.fps = 50; 
game.playerX = 50; 
game.playerY = 50; 


game.draw = function() { 

    c = document.getElementById('canvas'); 
    ctx = c.getContext("2d"); 
    clearCanvas(); 
    //PLAYER 
    ctx.fillStyle = "blue"; 
    ctx.fillRect(game.playerX, game.playerY, 50, 50); 
    //ENEMY 
    ctx.fillStyle = "green"; 
    ctx.fillRect(200, 200, 50, 50); 

    //Coords 
    ctx.font = "20px Arial"; 
    ctx.fillStyle = "red"; 
    ctx.fillText(game.playerX, 400, 480); 
    ctx.fillText(game.playerY, 450, 480); 

}; 

game.update = function() {  
    document.onkeydown = function() { 
     switch (window.event.keyCode) { 
      case 87: 
       //up 
       --game.playerY; 
       break; 
      case 83: 
       //down 
       ++game.playerY; 
       break; 
      case 65: 
       //left 
       --game.playerX; 
       break; 
      case 68: 
       //right 
       ++game.playerX; 
       break; 
     } 
    }; 
    //COLLISION DETECTION 
    if (game.playerX <= 200 && game.playerX <= 250 && game.playerY >= 200 && game.playerY <= 250) { 
     alert("it worked!"); 
     game.playerX = 400; 

    } 
    //END OF COLLISION DETECTION  
}; 

game.run = function() { 
    game.update(); 
    game.draw(); 
}; 

game.start = function() { 
    game._intervalId = setInterval(game.run, 1000/game.fps); 
}; 

game.stop = function() { 
    clearInterval(game._intervalId); 
}; 

回答

0

你想if(game.playerX >= 200而非if(game.playerX <= 200。現在你正在檢查playerX是否小於200且小於250,哪50個滿足。

+0

啊謝謝我看到我做了什麼 – user2580555

0

您正在使用不合適的鍵盤碼:JavaScript Keycodes。另外,當您手動調用game.update()時,您只會執行一次碰撞檢查。您需要將keydown事件中運行碰撞檢查:

這裏是一個Fiddle

document.onkeydown = function (e) { 
    switch (e.keyCode) { 
     case 38: 
      //up 
      console.log('up'); 
      --game.playerY; 
      break; 
     case 40: 
      //down 
      ++game.playerY; 
      break; 
     case 37: 
      //left 
      --game.playerX; 
      break; 
     case 39: 
      //right 
      ++game.playerX; 
      break; 
    } 

    console.log(game.playerX + ', ' + game.playerY); 

    //COLLISION DETECTION 
    if (game.playerX >= 200 && game.playerX <= 250 && game.playerY >= 200 && game.playerY <= 250) { 
     alert("it worked!"); 
     game.playerX = 400; 
    } 
};