2016-07-08 77 views
3

我正在研究一種名爲「捕捉墜落的物體」的簡單遊戲。在桌面設備上,遊戲運行良好且平穩。當您按下左右鍵時,「太空火箭」(使用以下鏈接查看遊戲)正在平滑移動x軸。現在在移動設備上,我遇到了一個小問題。當您按下「太空火箭」的左側或右側時,移動正常。但是當你按住「火箭」時,它並沒有按照你在屏幕上按下的方向移動。如果你鬆開你的手,你會看到火箭從一個位置跳到另一個位置,並且沒有像在桌面上一樣的平滑移動。我做了下面的代碼,但不能正常工作如何使畫布上的對象在移動設備上平滑地左右移動x軸

更新2

var mc = new Hammer(htmlCanvas); 
mc.add(new Hammer.Press({ event: 'press', time:1 })); 
mc.on("press", function(ev) { 
    console.log("dsaDS"); 
    touchDown = true; 
setInterval(function(){ 
    while(touchDown) { 
     console.log("down"); 
      if (ev.center.x < player.x) 
      { 
       player.x -= Math.floor(CANVAS_WIDTH/player.width); 
      } 
      else 
      { 
       player.x += Math.floor(CANVAS_WIDTH/player.width); 
      } 

      if (ev.center.x == player.x) 
      { 
       touchDown = false; 
      } 

    } }, 1000); 
}); 

mc.on("pressup", function(ev) { 
    touchDown = false; 
    console.log("up"); 
}); 

任何人都可以提出一個更好的解決方案?下面是遊戲 Game的鏈接,這是我遊戲的完整代碼code

更新1:這是行不通的任何設備上,iOS和Android

更新2:我已經改變了方式我檢測衝壓機屏幕

+0

這是一個很好的書面質詢,但仍有細節缺失;哪些移動設備? IOS? Android的?哪些版本?什麼瀏覽器? –

+1

僅僅基於猜測,我認爲問題是'while(touchdown)',讓特定的線程(或者在設備中實現)太忙而無法更新屏幕。你可以把這個動作放在一個'setInterval'中(間隔很小),它是在接地時開始的,並在接觸時停下來的? –

+1

你不應該在你的事件處理程序中做你的遊戲邏輯。 IO事件處理程序用於註冊IO事件,事件可以以任何速度和任何數量進入(觸摸事件以巨大的速率進入,這就是您的玩家跳轉的原因)。只是標記觸摸已關閉,然後在主循環中使用該信息更新您的播放器,這樣您就可以控制播放器的移動方式和時間。不要緊,如果你錯過了事件 – Blindman67

回答

0

與@ Me.Name和@ Blindman67幫助,我想出了一個解決方案,它是以下

function move(touchDown) 
{ 
    if(touchDown) 
    { 
     touchMoves = setTimeout(function(){ 
      if (Math.floor(touchX) < Math.floor(player.x + player.width)) 
      { 
       if ((Math.floor(player.x + player.width) - Math.floor(touchX)) <= 10) 
       { 
        touchDown = false; 
        clearTimeout(touchMoves); 
       } 
       else 
       { 
        player.x -= Math.floor(CANVAS_WIDTH/player.width); 
       } 

      } 
      else if ((Math.floor(touchX) == Math.floor(player.x + player.width)) || (player.x == (CANVAS_WIDTH - player.width))) 
      { 

       touchDown = false; 
       clearTimeout(touchMoves); 
      } 
      else 
      { 
       if ((Math.floor(touchX) - Math.floor(player.x + player.width)) <= 10) 
       { 
        touchDown = false; 
        clearTimeout(touchMoves); 
       } 
       else 
       { 
        player.x += Math.floor(CANVAS_WIDTH/player.width); 
       } 
      } 

      if (touchDown) 
      { 
       move(touchDown); 
      } 

     }, 100); 
    } 
} 
mc.on("press", function(ev) { 
    if (gameIsActive) 
    { 
     touchDown = true; 
     touchX = ev.center.x; 
     move(touchDown); 
    } 

}); 

mc.on("pressup", function(ev) { 
    if (gameIsActive) 
    { 
     touchDown = false; 
    } 
}); 
相關問題