2015年4月28日 星期二

[Corona SDK] How to detect double-tapped?

If we want to check if user has touched the screen, we can use Tap Detection or Touch Detection.
If we want to know if user has double-tapped the screen, to use Tap Detection is better.
Example shown as below:
local function buttonListener( event )

    if ( event.numTaps == 1 ) then
        print( "single-tapped" )
        runSingleTappedAction()
    elseif ( event.numTaps == 2 ) then
        print( "double-tapped" )
        runDoubleTappedAction()
    else
        return true
    end
end

local myButton = display.newRect( 160, 240, 120, 60 )
myButton:addEventListener( "tap", buttonListener )
For double-tapped, it will happen following single-tapped event.
That is, it will execute runSingleTappedAction() first, and then execute runDoubleTappedAction().
What if we do not want to execute runSingleTappedAction() for double-tapped event?
To achieve that, we should wait for a while before running action, since we need to confirm if it is single-tapped or double-tapped.
Example shown below:
local tapCount=0
local timeId = nil
function runTapAction( event )
 if ( tapCount == 1 ) then
     print( "single-tapped" )   
     runSingleTappedAction() 
 elseif ( tapCount == 2 ) then
     print( "double-tapped" )
     runDoubleTappedAction()
 end
end

local function buttonListener( event )
 tapCount = event.numTaps
 if(timeId ~= nil) then
   timer.cancel( timeId )
 end
 timeId = timer.performWithDelay( 200, runTapAction,1 )
end

local myButton = display.newRect( 160, 240, 120, 60 )
myButton:addEventListener( "tap", buttonListener )
Of course, we will sacrifice the response time for single-tapped event.

沒有留言:

張貼留言