system.activate( "multitouch" )
local box = display.newRect( 0, 0, 320, 480)
local touches = {}
local debug = display.newText("Number of fingers down:", 20, 30, system.nativeFont, 16)
debug:setTextColor(0, 0, 0)
function onTouch( event )
local target = event.target
local id = event.id
local phase = event.phase
if phase == "began" then
table.insert(touches, id)
elseif phase == "ended" or phase == "cancelled" then
for i,v in ipairs(touches) do
if touches[i] == id then
table.remove(touches, i)
end
end
end
debug.text = "Number of fingers down: " .. #touches
end
box:addEventListener('touch', onTouch)
I was messing around with this the other day. The key thing you need to know is that for multi touch events u will get a second event, even if the first one hasn't ended. i.e. two "begin" events (one for each finger) before any "end" event. Therefore you need to track the first finger and see if there was every another one BEFORE it was lifted (ended).
Since you normally use both fingers attributes, like 'x' to do things you usually want to store that information in a table, so you can access it. Thats what the example does.
However if all you want to do is say move a shape with two fingers you don't need to bother storing the second event stuff.
Here's an example that will let you do whatever you like using the FIRST fingers co-ordinates, but only if more than one finger is down. You could add if t.numberToucher == 1, or 2 , or 3 (at the point i marked with a (*), if you want to do different things for different amount of fingers down,
Remember this only tracks information of the first finger tho. For things like pinch zoom etc where u need to know the distance between fingers you need to store that information.
Hope it helps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| onTouch = function( event )
local t = event.target
local phase = event.phase
if "began" == phase then
if t.numberTouches == nil then
-- First finger touch, initialise
t.numberTouches = 1
t.multiTouch = false
t.firstFingerEvent = event.id
else
-- More than 1 finger, increase count
t.multiTouch = true
t.numberTouches = t.numberTouches + 1
end
elseif ("move" == phase ) then
-- Check for multitouch, and that this is the move for the first finger
if t.multiTouch then
if event.id = t.firstFingerEvent then
-- (*) all coordinates etc of event are of the FIRST finger. Do whatever you want here
-- eg. movesomething(event.x, event.y)
end
else
-- Do whatever for single touches
end
elseif ("ended" == phase or "cancelled" == phase) and t.x0 ~= nil and t.y0 ~= nil then
t.numberTouches = t.numberTouches - 1
if t.numberTouches == 0 then
t.numberTouches = nil -- All touches done nil out for next time
end
if not t.multiTouch then
t.numberTouches = nil -- All touches done nil out for next time
-- Do whatever for single touches
end
end
end
<code> |