Rotate an object as long as touching a button

In my game I want to implement a touch feature that as long as the button pressed the object will rotate and stop rotating as soon as touch event ends. How can I implement that? I did it with “tap” event which is not I wanted and it has many flaws.

You can solve it using the touch event instead (And the event phases “began”, “ended” and “cancelled”). To keep the focus on your object you may also need to use setFocus

1 Like

In order to pull this off, you’ll likely want to use an enterFrame listener, but, like depilz said, you’ll want to use a touch event listener for this.

Here’s a quick way of doing it. Mind you that this code is far from perfect.

local currentTarget
local function rotate()
  currentTarget.rotation = currentTarget.rotation+1

local function touch( event )
  if event.phase == "began" then
    display.getCurrentStage():setFocus( )
    currentTarget =
    Runtime:addEventListener( "enterFrame", rotate )
  elseif event.phase == "ended" then
  	display.getCurrentStage():setFocus( nil )
    Runtime:removeEventListener( "enterFrame", rotate )
    currentTarget = nil

local object = display.newRect( 600, 100, 100, 100 )

object:addEventListener( "touch", touch )
1 Like