Easily Create Several Images with Corona SDK

A common function when creating games is to display several on screen images as once. In your game, you may want to display a series of clouds, rocks, balloons, or anything else. Instead of writing the code for every single image, you could write a simple loop to do this for you.

By creating a simple loop to create your images, it’s not only less code, but the loop will make editing your code easier in the future.

Here’s the code:

letterHolder = {} -- initialize array
numOfImages = 10 -- define how many images on what on screen

for i=1,numOfImages do -- start for loop to go from 1 to 10
 letterHolder[i] = display.newRect(0,0,20,20) -- create a new rectangle and store it in the letterHolder array
 letterHolder[i]:setFillColor(math.random(1,255), math.random(1,255), math.random(1,255)) -- assign a random color
 letterHolder[i].x = math.random(0, display.contentWidth) -- display the rectangle in a random x position on screen
 letterHolder[i].y = math.random(0, display.contentHeight) -- display the rectangle in a random y position on screen
end

I’ve put comments inside the code to help explain each line. Basically, I initialized the variables, created a for loop and assigned it a random color with a random location. Here’s a screenshot of what you should end up with.

If you wanted to use an image instead of a rectangle, you would swap out line 5 for display.newImageRect() instead.

letterHolder = {} -- initialize array
numOfImages = 10 -- define how many images on what on screen

for i=1,numOfImages do -- start for loop to go from 1 to 10
 letterHolder[i] = display.newImageRect("myImage.png", 20, 20) -- create a new image and store it in the letterHolder array
 letterHolder[i]:setFillColor(math.random(1,255), math.random(1,255), math.random(1,255)) -- assign a random color
 letterHolder[i].x = math.random(0, display.contentWidth) -- display the rectangle in a random x position on screen
 letterHolder[i].y = math.random(0, display.contentHeight) -- display the rectangle in a random y position on screen
end

As you can see, this makes it really easy to create a collection of on screen images with fewer lines of code. If you have any questions or comments, please leave them below. Thanks for reading this tutorial for Corona SDK by Game Building Tools!

Leave a Reply

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