What's the anatomy of a touch?

Would it be possible to have a few documents on the more iPad-specific aspects of programming with Codea? I feel that I can figure out most things from general hacking experience, but there are a few bits that seem destined to trip me up.

The one that prompted this was the touch mechanism. I figured out that a touch BEGAN, then was MOVING, and finally ENDED. But it seems that the BEGAN can last longer than a frame, is that true? From one of the sample programs then I got the idea of having a touchHandled boolean. Are there any other tips and tricks for using touches, or particular examples that I should look at to see how it works?

function touched(touch)

Gets called once for each touch, for each touch state change. Two occurrences of BEGAN might indicate that two touches have just started. I found that an easy way to handle multiple touches was to do the following:

function setup()
    touches = {}

function touched(touch)
    if touch.state == BEGAN then
        touches[touch.id] = touch
    elseif touch.state == ENDED then
        touches[touch.id] = nil

    processTouches() -- do more stuff with touches...

All this does is keep a global table, adding touches keyed under their ID (which is unique per touch) and deleting them when they end. You can then process all touches every frame. The multi touch example does this to render different coloured dots under each finger every frame.

I’ve done a little hacking in my projects to detect if a finger is being held in one spot. Just check if the MOVING touch’s velocity vector is short and, if it’s not already in a holding[] table, make an entry set to ElapsedTime. If it starts moving again then clear the entry. Then, when I process the touches, I check how long the touch has been held and do different things. As soon as I have my Conway’s project cleaned up I’ll post the code, I’m using a “hold one finger to target and double tap with another to fire a glider toward the target” gesture. Feels intuitive.

Touch.tapCount is insanely useful for adding more gestures as well, and it doesn’t stop at double or triple tap either.

Also, have a look at my controllers library: https://github.com/npryce/codea-controllers

It defines a few classes for interpreting touches (tap actions, virtual joystick, catapult) and dispatching touches to controllers in various ways (split screen, Jeff Minter-style game controls)

Simeon, so that function gets called asynchronously, is that it? I don’t need to check for touches in the draw function.

Is this “safe”? In that, can I assume that a draw function will be completed or might it get interrupted half way?

touched is called either before or after draw, depending on when the OS decides to send Codea the events. Its not asynchronous in the parallel programming sense and cannot interrupt the draw call.

That’s good. I like that.