2016-10-22 129 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 

请注意,您仍应删除“结束/取消”阶段的触摸。

编辑:在屏幕的同一侧可能会有多个触摸,所以要么忽略新的触摸,要么以某种方式平均它们。