touch

Type Event
Revision Release 2024.3703
Keywords touch
See also Tap/Touch/Multitouch (guide)

Overview

When the user’s finger touches the screen, a hit event is generated and dispatched to display objects in the display hierarchy. Only those objects that intersect the hit location (the location of the finger on the screen) will be candidates for receiving events.

Multitouch events are an extension of single touch events. Multitouch is enabled by the system.activate() API.

Properties

event.id

event.name

event.phase

event.pressure

event.target

event.time

event.x

event.xStart

event.xDelta

event.y

event.yStart

event.yDelta

Examples

Function Listener
local object = display.newImage( "ball.png" )
object.id = "ball object"

local function onObjectTouch( event )
    if ( event.phase == "began" ) then
        print( "Touch event began on: " .. event.target.id )
    elseif ( event.phase == "ended" ) then
        print( "Touch event ended on: " .. event.target.id )
    end
    return true
end
object:addEventListener( "touch", onObjectTouch )
Table Listener 1
local object = display.newImage( "ball.png" )
object.id = "ball object"

local function onObjectTouch( self, event )
    if ( event.phase == "began" ) then
        print( "Touch event began on: " .. self.id )
    end
    return true
end 

object.touch = onObjectTouch
object:addEventListener( "touch", object )
Table Listener 2
local object = display.newImage( "ball.png" )
object.id = "ball object"

function object:touch( event )
    if ( event.phase == "began" ) then
        print( "Touch event began on: " .. self.id )
    end
    return true
end 
object:addEventListener( "touch", object )
Comprehensive
local object = display.newImage( "ball.png" )
object.id = "ball object"

function object:touch( event )
    if ( event.phase == "began" ) then
        print( "Touch event began on: " .. self.id )

        -- Set touch focus
        display.getCurrentStage():setFocus( self )
        self.isFocus = true
    
    elseif ( self.isFocus ) then
        if ( event.phase == "moved" ) then
            print( "Moved phase of touch event detected." )

        elseif ( event.phase == "ended" or event.phase == "cancelled" ) then

            -- Reset touch focus
            display.getCurrentStage():setFocus( nil )
            self.isFocus = nil
        end
    end
    return true
end 
object:addEventListener( "touch", object )