Last active
April 19, 2021 11:52
-
-
Save XeduR/6b82b6fe2b480957dacd02e9ffd41b74 to your computer and use it in GitHub Desktop.
A method for forcibly cancelling touch events in Solar2D programmatically regardless of the active touch event's phase.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local masterTouch | |
local function cancelTouch() | |
if masterTouch then | |
print( "\nTouch event phase before cancellation: " .. masterTouch.phase ) | |
-- You could include a unique property to know that the event was terminated via this function. | |
-- masterTouch.terminated = true | |
masterTouch.phase = "cancelled" -- Change the event phase before faking the touch event. | |
masterTouch.target.listener( masterTouch ) | |
-- Setting isTouched property back to false will prevent the touch listener from firing again | |
-- until the user manually ends the touch event and starts it again from the "began" phase. | |
masterTouch.target.isTouched = false | |
masterTouch = nil | |
end | |
end | |
-- Display information on event as it was cancelled (either manually or via timer). | |
local function eventInfo( info ) | |
print("------------------") | |
print("TOUCH EVENT ENDED:") | |
print("------------------") | |
for i, v in pairs( info ) do | |
print(i,v) | |
end | |
print("------------------") | |
end | |
local function listener( event ) | |
-- masterTouch needs to be set within different phases, because otherwise it won't ever be nil. | |
if event.phase == "began" then | |
event.target.isTouched = true | |
masterTouch = event | |
elseif event.target.isTouched then | |
if event.phase == "moved" then | |
masterTouch = event | |
else | |
if event.phase == "ended" then | |
masterTouch = nil | |
end | |
eventInfo( masterTouch or event ) | |
end | |
end | |
return true | |
end | |
local button = display.newRect( display.contentCenterX, display.contentCenterY, 100, 100 ) | |
button:addEventListener( "touch", listener ) | |
button.listener = listener | |
-- Cancel the touch event automatically. | |
timer.performWithDelay( 1500, cancelTouch ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment