SSK2 - Button Release

Hello Solar2D Forums,

How can I get the event when a button is no longer being pressed?:

I’ve tried writing my own scripts but there’s always a weird form of interaction that passes through. SSK2 brilliantly deals with such instances but the onRelease event is only called when the touch is released on the button itself (like the “ended” phase), even though interactions like touching the button then sliding your finger off are clearly detected.

You can set a flag when it’s being pressed and change it to false when it’s not.

Something like this:

local function handleTouch(event)
	if (event.phase == "began") then
		display.getCurrentStage( ):setFocus( ) = true

		print ("began",
	elseif (event.phase == "moved") then
		print (
	elseif (event.phase == "ended" or event.phase == "cancelled") then
		display.getCurrentStage( ):setFocus( nil ) = false

		print ("ended",
	return true

local rect = display.newRect( display.contentCenterX, display.contentCenterY, 150, 150 )
rect.isPressed = false
rect:addEventListener( "touch", handleTouch )

The SSK2 buttons library, does the following:

  • touch began - start tracking touch
  • touch moved - check to see if touch is within bounds of button and show the appropriate selected or not-selected image.
  • touch ended - check to see if the touch is within the bounds of the button. If so, take the onRelease action the user specified when creating the button. If not, do not take the action.

You can see the code here (~line 1112):

Be aware, the library uses a unified listener for all buttons and button types (push, radio, toggle, slider) so there is a lot going on in that listener. (Additionally, I support 2, 3, and 4 state buttons, so that might be a little confusing)

How can I detect the event when the touch is moved out of bounds?

If you use display.getCurrentStage():setFocus( ) in your touch listener, like in @bgmadclown’s sample code, then the touch event will remain active even if you drag your finger/cursor outside of the button.

Then, depending on the desired accuracy and button shape, you need to just monitor the event.x and event.y location. For instance, with a simple rectangular button, if the event.x ever becomes smaller than the’s minimum x or larger than its maximum x, then you know it has moved out of bounds.

1 Like