2016-10-22 20 views
0

私のゲームでは、私はタッチイベントを使ってオブジェクトをコントロールします。画面の右半分に触れるとオブジェクトが回転し、画面の左半分をタッチするとオブジェクトが動きます。ワンタッチでは完全に機能しますが、画面のいずれかの面に触れてからもう一度タッチすると、予期しない混乱した動作になります。複数のタッチを検出する

私の質問は、複数のタッチを別々に区別する方法です。

system.activate("multitouch") 

    onTouch = function (event) 

    if (event.phase == "began") then 
     pX = event.x  -- Get start X position of the touch 
     print("ID:"..tostring(event.id)) 
     if (event.x > centerX) then  --if the touch is in the right or left half of the screen 
      xPos = "right" 
     else 
      xPos = "left" 
     end 

    elseif (event.phase == "moved") then 
     local dX = (event.x - pX) 
     if (xPos == "right") then 
      rotatePlayer(dx) 
     else 
      movePlayer(dX) 
    end 

更新:

system.activate("multitouch") 

local touchID = {}   --Table to hold touches 

onTouch = function (event) 

    if (event.phase == "began") then 

     print("ID:"..tostring(event.id)) 
     if (event.x > centerX) then  --if the touch is in the right or left half of the screen 
      touchID[event.id] = {} 
      touchID[event.id].x = event.x 
      xPos = "right" 
      pX = touchID[event.id].x  -- Get start X position of the touch 
     else 
      touchID[event.id] = {} 
      touchID[event.id].x = event.x 
      xPos = "left" 
      pX = touchID[event.id].x 
     end 

    elseif (event.phase == "moved") then 
     print("ID:"..tostring(event.id)) 

     local dX 
     if (xPos == "right") then 
      touchID[event.id].x = event.x 
      dX = touchID[event.id].x - pX 
      rotatePlayer(dx) 
     else 
      touchID[event.id].x = event.x 
      dX = touchID[event.id].x - pX 
      movePlayer(dX) 
    end 

同じ問題がまだ存在しています。

答えて

0

event.idフィールドを無視しているようです。そのため、複数のタッチの動作が混在しています。

beganフェーズになると、新しいリストにいくつかのリストを保存することで、それぞれの新しいタッチを追跡できます。タッチの初期座標(あなたのpXがそこに行く)と後で必要なものを含めてください。他のイベント(移動/終了/キャンセル)が表示されたら、アクティブなタッチのリストを確認し、実際のタッチをevent.idで見つけ、その正確なタッチのロジックを実行する必要があります。

+0

タッチIDをテーブルに追加してタッチで移動しようとしましたが、同じ問題が引き続き存在します。更新された質問を確認してください。 – Abdou023

0

あなたはまだデータに触れています。 xPosはタッチ関数なので、タッチイベントに格納する必要があり、別のタッチからのデータで更新されるグローバル変数には格納しないでください。

また、ifブランチから重複した行を移動すると、それらは同じです。コードはより簡単になり、読みやすく理解しやすくなります。

system.activate("multitouch") 

local touchID = {}   --Table to hold touches 

onTouch = function (event) 
    local x, id, phase = event.x, event.id, event.phase 
    print("ID:"..tostring(id)) 

    if (phase == "began") then 
     touchID[id] = { 
      x = x, 
      logic = (x > centerX) and rotatePlayer or movePlayer 
     } 
    elseif (phase == "moved") then 
     local touch = touchID[id] 
     touch.logic(x - touch.x) 
    end 
end 

「終了/キャンセル」フェーズでタッチを削除する必要があります。

編集:画面の同じ面に複数のタッチがある可能性があるため、新しいタッチを無視するか、何らかの理由で平均します。

関連する問題