Just to simplify how this works:
When you touch the screen, Solar2D will check if there are any objects sitting directly under the touch.
It also checks whether any of those objects are listening for touch events (i.e. did any of them have a touch event listener added: myObject:addEventListener("touch", myTouchfunction)
).
It then notifies all of the ‘touchable’ objects of the touch event, starting with the top object and working its way down to the bottom of the pile.
Adding return true
to the end of a touch function is a way of telling Solar2D “if this object gets touched, it will handle the touch event - no need to check if other objects below are also listening for touch events”.
One more thing to keep in mind is that the touch event only gets applied to the object while you’re finger is directly on it, so it you start a touch on one object and move your finger very quickly onto another you may find that the “began” phase is triggered on the first object, but the “ended” phase is on the other. To prevent this from happening, you can ‘lock’ the touch onto the event so that the began, moved and ended phase all get passed to the same touch listener function even if you move away from the object.
You just need to remember to remove this lock when the touch ends. Example:
local myObject = display.newRect(0, 0, 50, 50)
function myObject:touch( event )
if ( event.phase == "began" ) then
-- This locks the touch onto the object
display.getCurrentStage():setFocus( self )
--this is a common shorthand way of keeping track of whether we have locked the touch to the object
self.isFocus = true
elseif ( self.isFocus ) then
if ( event.phase == "moved" ) then
--do your movement stuff here
elseif ( event.phase == "ended" or event.phase == "cancelled" ) then
--Passing nil to this function unlocks the touch from the object, so that the next touch can be applied to any object
display.getCurrentStage():setFocus( nil )
self.isFocus = nil
end
end
--this is the critical part to letting Solar2D know not to pass the touch event on to any more objects
return true
end
myObject:addEventListener( "touch", myObject )