In Corona SDK, How do I get an object to keep moving while touching the background screen?

Here’s the situation. I want a square object to continuously move in y-direction as long as I’m touching the screen. Based on the code, I have it should give me a continuous movement of the square object, but, only when I’m sliding with my finger on the touch screen, the object moves. I want the square object to continuously move when I’m touching the screen on the same spot.

I tried using both timer and runtime event listener to no avail. What’s the fix here?

local squareTimer

local function squareMoveUp()
    square.y = square.y - 5
end    
   
local holding = ‘false’
local function startMove(event)
    if event.phase == ‘began’ then
        --Runtime:addEventListener(‘enterFrame’,squareMoveUp)  
        squareTimer = timer.performWithDelay(200,squareMoveUp,0)
        
    elseif event.phase == ‘ended’ then
        --Runtime:removeEventListener(‘enterFrame’,squareMoveUp)
    end
    return true
end

background:addEventListener(‘touch’,squareMoveUp)
 

Hi @danpreneur,

It looks like you’re pointing the touch listener on “background” to call the “squareMoveUp()” function. So, it only occurs once. Instead, it should be calling the “startMove()” function, which of course calls the other function from within.

Everything else looks basically OK, except that if you use timers, you should use “timer.cancel()” on the same “squareTimer” reference during the “ended” phase so that the square actually stops (well, more accurately, stop/cancel the timer which repeatedly calls the movement function).

Also, it’s best practice to include the “cancelled” phase in the same condition as the “ended” phase for uncommon (but potential) times when the OS itself cancels the current touch:

[lua]

elseif ( event.phase == ‘ended’ or event.phase == ‘cancelled’ ) then

[/lua]

Brent

See this tutorial: https://coronalabs.com/blog/2014/02/04/tutorial-continuous-actions-in-corona/

Rob

Hi @danpreneur,

It looks like you’re pointing the touch listener on “background” to call the “squareMoveUp()” function. So, it only occurs once. Instead, it should be calling the “startMove()” function, which of course calls the other function from within.

Everything else looks basically OK, except that if you use timers, you should use “timer.cancel()” on the same “squareTimer” reference during the “ended” phase so that the square actually stops (well, more accurately, stop/cancel the timer which repeatedly calls the movement function).

Also, it’s best practice to include the “cancelled” phase in the same condition as the “ended” phase for uncommon (but potential) times when the OS itself cancels the current touch:

[lua]

elseif ( event.phase == ‘ended’ or event.phase == ‘cancelled’ ) then

[/lua]

Brent

See this tutorial: https://coronalabs.com/blog/2014/02/04/tutorial-continuous-actions-in-corona/

Rob