Corona SDK – Scrolling landscape

Here are a few ideas to get started creating a scrolling background. Create a background image that repeats, where the left edge would tile seamlessly when connected to the right edge. Copy a section the size of the visible area of the screen and add it to the right side of the image.

Here are a couple images for example. Look at the images carefully and you will see the the 480 pixels on the right side match the first 480 pixels on the left.

Landscape-1

 

Landscape-2 Landscape-3
These images link to the originals at full size. You can download them to use with the example code which follows.

 

Here’s a simple example that works with a single image.

 

local landscape = display.newImageRect( "landscape-1.png", 1440, 320 )

-- landscape:setReferencePoint( display.TopLeftReferencePoint )
landscape_1.anchorX = 0
landscape_1.anchorY = 0
landscape_1.x = 0
landscape_1.y = 0

local function reset_landscape( landscape )
	landscape.x = 0
	transition.to( landscape, {x=0-1440+480, time=30000, onComplete=reset_landscape} )
end

reset_landscape( landscape_1 )

Here’s an example that takes the code above and turns it into a function allowing you to create more animated landscapes without having to duplicate the code.


local function make_landscape( image, width, height, time )
	local landscape = display.newImageRect( image, width, height )

	-- landscape:setReferencePoint( display.TopLeftReferencePoint )
	landscape.anchorX = 0
	landscape.anchorY = 0	
	landscape.x = 0
	landscape.y = 320 - height
	landscape.time = time
	
	local function reset_landscape( landscape )
		landscape.x = 0
		transition.to( landscape, {x=0-landscape.width+480, time=landscape.time, onComplete=reset_landscape} )
	end
	
	reset_landscape( landscape )
	
	return landscape
end 

local landscape_group = display.newGroup()

local landscape_1 = make_landscape( "Landscape-1.png", 1440, 86, 10000 )
local landscape_2 = make_landscape( "Landscape-2.png", 1440, 168, 20000 )
local landscape_3 = make_landscape( "Landscape-3.png", 1440, 215, 30000 )

landscape_group:insert( landscape_3 )
landscape_group:insert( landscape_2 )
landscape_group:insert( landscape_1 )

Leave a Reply

Your email address will not be published. Required fields are marked *