No products in the cart.
Hello and welcome to another quick tutorial for Corona SDK!
If you have a large sized game, there comes the time where you might need a loading graphic to show the player you are downloading graphics or loading them into texture memory. In this quick tutorial, you’ll discover how to build a simple loading bar with a function to update it. Similar to my other tutorials, I’ve left comments next to each section to explain what is happening in the code.
-- Create variables for the width, height, and corners of our loading bar local loadingWidth, loadingHeight, loadingCorners = 400, 100, 10 -- Create the loading bar background. This background is white and placed on the center of the screen. local loadingBarBackground = display.newRoundedRect(0,0,loadingWidth,loadingHeight,loadingCorners) loadingBarBackground.x, loadingBarBackground.y = display.contentWidth * 0.5, display.contentHeight * 0.5 -- Create the actual loading bar that will move. We'll make this loading bar a bit smaller than the background so the user can see the progress a bit easier. The xScale is set to 0.001 so it's hidden when it first loads. local loadingBar = display.newRoundedRect(0,0,loadingWidth*0.975,loadingHeight*0.925,loadingCorners) loadingBar.anchorX = 0 loadingBar.x, loadingBar.y = loadingBarBackground.x - (loadingWidth * 0.4875), loadingBarBackground.y loadingBar:setFillColor(190/255, 33/255, 33/255) loadingBar.xScale = 0.001 -- This function will update based on a percentage. Pass in values like 10, 40, or 50 to update the percentage to 10%, 40%, or 50% respectively. local function updateLoading(percent) loadingBar.xScale = percent / 100 end
Once you have this in place, you can call the updateLoading() function to change the scale of the bar. For example, you could pass in updateLoading(10) or updateLoading(40) to move the bar to 10% or 40% respectively. Or, you could use a timer to update the loading bar by one percent every second. Here’s you could use a timer.
local counter = 0 -- Create a counter local function doSomething() -- create the function updateLoading(counter) -- pass in the counter to updateLoading() counter = counter + 1 -- increase counter by 1 end timer.performWithDelay(1000, doSomething, 100) -- run the timer every second 100 times to reach 100%
And that’s it for building a loading bar with Corona SDK! You could replace the native objects with your own images to make the bar more visually appealing. If you have questions, leave them below!