Below is a simple Lua program of a shelf moving left and right across the screen. When the screen is tapped, the shelf is supposed to reset and start at the left again. But after that, the transitions.to do not work properly, as the shelf starts "jumping" back and forth. Can someone please help me fix this issue?
local shelf
local function movingShelf()
shelf = display.newRect(56.5,250,85,10) --display shelf
local moveLeft --move shelf
local function moveRight()
transition.to(shelf, {time = 5000, x = 261, onComplete = moveLeft})
end
moveLeft = function()
transition.to(shelf, {time = 5000, x = 57.5, onComplete = moveRight})
end
moveRight()
end
local function restart() -- restart the program
shelf:removeSelf()
movingShelf()
end
movingShelf()
Runtime:addEventListener("tap", restart) -- tap to restart
The transitions you initiate in moveLeft()
and moveRight()
are applied to shelf
and you haven't cancelled them. This can cause this kind of glitchy behavior.
To properly remove a DisplayObject, you need to cancel any transitions it is involved in. In your restart
function, you should do transition.cancel( shelf )
before removing the DisplayObject with shelf: removeSelf()
. Finally, add shelf=nil
for good measure (doing so is the recommended practice when removing DisplayObjects in Corona to avoid memory leaks).