This is really just me thinking aloud, but hopefully if I think something stupid then someone’ll hear my thinking and put me out of my misery.
I’m trying to understand exactly how a touch works so that I can better handle multiple touches and taps. Here’s my code that I’m experimenting with:
function setup()
x = WIDTH/2
y = HEIGHT/2
c = color(255,255,0,255)
frame = 0
end
function draw()
background(0, 0, 0, 255)
frame = frame + 1
fill(c)
ellipse(x,y,100)
end
function touched(touch)
x = touch.x
y = touch.y
local status, taps
if touch.state == BEGAN then
status = "began"
c = color(255,0,0,255)
frame = 0
end
if touch.state == MOVING then
status = "moving"
c = color(0,255,0,255)
end
if touch.state == ENDED then
status = "ended"
c = color(255,255,0,255)
end
if touch.tapCount == 1 then
taps = ""
else
taps = "s"
end
print(status .. ", " .. frame .. " frames, " .. touch.tapCount .. " tap" .. taps)
end
What I see is that touch events are only registered when something happens. So a touch can begin and then wait a while before anything more happens - if you have a steady finger!
This makes life a little complicated if one is trying to track changes with two touches. The temptation is simply to write change = touchA.deltaX + touchB.deltaX
. This is fine if both touches changed. If only one touch changed, then as the other one has not been updated, its delta is still the same. So when dealing with two touches, one wants an overlay object which gets updated every cycle no matter what.
Moreover, this testing suggests that the documentation is subtly wrong. It says that the deltaX and deltaY are the amount that the touch has moved since the previous frame. It appears that this is since the previous change to the touch. Namely, even if there are several frames between touch events, the delta is the difference between them.
With taps, it appears that the tap count follows the touch.id and is incremented if there was a “tap” at the same location (presumably within some plus-minus) within some time limit. A “tap” is a touch that has just a beginning and an ending. Because of what I said above, a tap can last a long time if you are very steady. I guess that this is the secret behind “long taps”. Again, to properly process these events one would need a more robust touch object.
So for a complicated project, I’m thinking that the following would be a reasonable way to cleanly work with touches.
- A new Touch class which was meant to deal with a whole touch, not just its events.
- In the
touched
function, we initiate, update, and destroy these objects according to the new data. - At the start of the
draw
function, we process the current state of play vis-a-vis the Touches that are active.