在我的游戏中,我使用触摸事件控制对象。当我触摸屏幕的右半部分时,对象会旋转,当我触摸屏幕的左半部分时,对象会移动。只需单次触摸即可完美运行,但当我触摸屏幕的任何一侧,然后同时开始触摸另一侧时,会导致意外的混合行为。
我想我的问题是,如何分离或区分多个触摸彼此。
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 :(得分:0)
似乎你忽略了event.id
字段,这就是为什么你混淆了多个触摸行为。
当您获得began
阶段时,通过将每个新触摸存储在某个列表中来跟踪每个新触摸。包括触摸初始坐标(您的pX
去那里)以及稍后您可能需要的任何其他内容。当您获得其他事件(移动/结束/取消)时,您应该检查活动触摸列表,找到event.id
的实际触摸并执行该触摸的逻辑。
答案 1 :(得分: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
请注意,您仍应删除“已结束/已取消”阶段的触摸。
编辑:屏幕同一侧可能有多个触摸,因此要么忽略新触摸,要么以某种方式对它们进行平均。