In today’s post, we will explain how to create a horizontal scrolling background in Corona SDK. This is a great and easy way to make your game more interesting. So let’s get started!
Our first step is to add the images to our game. We do that by using Corona’s display.newImageRect to add 3 background images to the game.
Here’s the code.
-- Add First Background local bg1 = display.newImageRect("images/bg1.png", 482, 320) bg1:setReferencePoint(display.CenterLeftReferencePoint) bg1.x = -50; bg1.y = _H/2; -- Add Second Background local bg2 = display.newImageRect("images/bg2.png", 480, 320) bg2:setReferencePoint(display.CenterLeftReferencePoint) bg2.x = 430; bg2.y = _H/2; -- Add Third Background local bg3 = display.newImageRect("images/bg1.png", 480, 320) bg3:setReferencePoint(display.CenterLeftReferencePoint) bg3.x = 910; bg3.y = _H/2;
In the first line of every background, we add the background to the game with display.newImageRect. The next line sets the Reference Point. In this case, we are setting the Reference Point to be the Center Left point. This means that when we position the graphic, the Center Left point will be used for the positioning. Finally, we set the x an y values of the background image.
Next, we’ll actually make the backgrounds move. We’ll use a Runtime listener to make our background move with Corona SDK.
local function move(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 + bg1.contentWidth) < -480 then bg1:translate( 480*3, 0 ) end if (bg2.x + bg2.contentWidth) < -480 then bg2:translate( 480*3, 0 ) end if (bg3.x + bg3.contentWidth) < -480 then bg3:translate( 480*3, 0 ) end end -- Create a runtime event to move backgrounds Runtime:addEventListener( "enterFrame", move )
This isn’t as complicated as it looks. Before we used the code above, we position our backgrounds by placing bg1 on the center of the screen, bg2 to the right of bg1 and bg3 to the right of bg1. When we utilize the Runtime listener, we move all backgrounds to the left according to the scroll speed. (This variable was initialized before the backgrounds and you can download the full source below).
When bg1, bg2 or bg3 hits a certain point (-480), the Runtime listener will move that background to the right of the screen. This is essentially resetting the position of the image. Once it’s reset, the background continues to move left. The effect is a horizontally scrolling background with Corona SDK!
As always, you can download the full source code below! If you have questions or comments, please leave them below!