Sunday, February 16, 2014

Setting up a moving background with Corona SDK

I just created a simple moving background written in lua for Corona SDK. The source is as follows:
-- TODO: add your own image-file, I have used a file called bg1.png
local scrollSpeed = 2
-- Add First Background
local bg1 = display.newImageRect("bg1.png", display.contentWidth, display.contentHeight)
bg1.x = 0; bg1.y = display.contentHeight/2;
local bg2 = display.newImageRect("bg1.png", display.contentWidth, display.contentHeight)
bg2.x = display.contentWidth; bg2.y = display.contentHeight/2;
-- Add Third Background
local bg3 = display.newImageRect("bg1.png", display.contentWidth, display.contentHeight)
bg3.x = display.contentWidth*2; bg3.y = display.contentHeight/2;
local function moveBg(event)
-- move backgrounds to the left by scrollSpeed, default is 8
bg1.x = bg1.x - scrollSpeed
bg2.x = bg2.x - scrollSpeed
bg3.x = bg3.x - scrollSpeed
-- Set up listeners so when backgrounds hits a certain point off the screen,
-- move the background to the right off screen
if (bg1.x ) < -display.contentWidth then
bg1:translate( display.contentWidth*3, 0 )
end
if (bg2.x ) < -display.contentWidth then
bg2:translate( display.contentWidth*3, 0 )
end
if (bg3.x ) < -display.contentWidth then
bg3:translate( display.contentWidth*3, 0 )
end
end
-- Create a runtime event to move backgrounds
Runtime:addEventListener( "enterFrame", moveBg )
view raw movingbg.lua hosted with ❤ by GitHub
Use it as you wish!