2017-07-10 83 views
0

我對javascript很新,我試圖做一個迷宮遊戲,我用箭頭移動和wasd,但我無法弄清楚如何使用html按鈕移動觸摸設備,這裏是我的js代碼:在html按鈕的JavaScript箭頭鍵移動

function moveRect(e) { 
     var estado = new Boolean(false); //variable to know if the player won or not 
     var pos = []; //saves every position player moves to 
     var newX; 
     var newY; 
     var canMove; // i'm not using this right now 
     e = e || window.event; 
     moveA = 22; //1 
     moveB = 22; //22 
     var angle = 0; 
     switch (e.keyCode) { 
      case 38: // upkey 
       newX = currRectX; 
       newY = currRectY - moveA; 
       angle = 90; 
       break; 
      case 87: // W key 
       newX = currRectX; 
       newY = currRectY - moveB; 
       angle = 90; 
       break; 
      case 37: // leftkey 
       newX = currRectX - moveA; 
       newY = currRectY; 
       angle = 180; 
       break; 
      case 65: // A key 
       newX = currRectX - moveB; 
       newY = currRectY; 
       angle = 180; 
       break; 
      case 40: // downkey 
       newX = currRectX; 
       newY = currRectY + moveA; 
       angle = 270; 
       break; 
      case 83: // S key 
       newX = currRectX; 
       newY = currRectY + moveB; 
       angle = 270; 
       break; 
      case 39: //rightkey 
       newX = currRectX + moveA; 
       newY = currRectY; 
       break; 
      case 68: // D key 
       newX = currRectX + moveB; 
       newY = currRectY; 
       break; 
      default: 
       return; 
     } 

現在我試圖找出如何將它添加到一個HTML按鈕,例如左鍵做什麼鍵,左鍵做。

我已經試過jQuery這樣

$('#left-btn').click(); 
$('#right-btn').click(); 

,但我不知道如何傳遞什麼我已經有編碼作爲click()的參數。

回答

0

你可以做你想做的一切。
不要忘記聲明你的變量超出該函數的範圍。

$('#left-btn').click(function(){ 
    //do your things here 
    //e.g. 
    x -= 10; 
    angle = 50; 
}); 

查看更多:
https://api.jquery.com/click/