In a lot of mobile games, you’ll find yourself dragging a character around the screen to complete a puzzle, fight enemies, or interact with other objects. Corona SDK has made it easy for you to implement this functionality.

In this tutorial, you’ll learn how to attach an event listener to an object. This event listener will allow the player to drag an object around the screen and the drag will stop when the player removes his or her finger from the screen. I’ll be working from one file, but you can feel free to use this code anywhere you see fit. Let’s jump in.

First, we are going to hide the status bar. This is only necessary when you are starting from scratch and should only appear in main.lua. Otherwise, feel free to skip this line.

— hide the status bar
display.setStatusBar(display.HiddenStatusBar)
Next, we’ll create a square. This square can be replaced with an image or another display object. In our example, the square object will be dragged around the screen.

— create a square and put it in the center of the screen
local square = display.newRect( 100, 100, 50, 50)
square:setFillColor( 1 )
Then, we’ll create a function that will be called when the object is touched. In this function, we’ll record the original x and y position in the began phase. The began phase occurs when the object is first interacted with. Then, the function will move on the to the moved phase and this phase will move our object according to the event. Finally, when the player stops interacting with the circle, we’ll remove the object focus so Corona knows we are done with the touch function.

— touch listener function
function square:touch( event )
if event.phase == “began” then
— first we set the focus on the object
display.getCurrentStage():setFocus( self, event.id )
self.isFocus = true

— then we store the original x and y position
self.markX = self.x
self.markY = self.y

elseif self.isFocus then

if event.phase == “moved” then
— then drag our object
self.x = event.x – event.xStart + self.markX
self.y = event.y – event.yStart + self.markY
elseif event.phase == “ended” or event.phase == “cancelled” then
— we end the movement by removing the focus from the object
display.getCurrentStage():setFocus( self, nil )
self.isFocus = false
end
end

— return true so Corona knows that the touch event was handled properly
return true
end
Finally, we’ll create an event listener and attach the listener to the square. This lets Corona know that it should listen for the touch event on the square.

— finally, add an event listener to our square to allow it to be dragged
square:addEventListener( “touch”, square )
And that’s it to making an object draggable in Corona SDK! If you have questions or comments about this short game tutorial, please leave them in the comments below. Thanks for reading.

p.s. In the tutorial above, the code is broken down into sections so I can explain what is occurring in the code. For those of you that would like to learn by doing, I’ve posted the code in one big chunk so you can copy/paste this into your project.

— hide the status bar
display.setStatusBar(display.HiddenStatusBar)

— create a square and put it in the center of the screen
local square = display.newRect( 100, 100, 50, 50)
square:setFillColor( 1 )

— touch listener function
function square:touch( event )
if event.phase == “began” then
— first we set the focus on the object
display.getCurrentStage():setFocus( self, event.id )
self.isFocus = true

— then we store the original x and y position
self.markX = self.x
self.markY = self.y

elseif self.isFocus then

if event.phase == “moved” then
— then drag our object
self.x = event.x – event.xStart + self.markX
self.y = event.y – event.yStart + self.markY
elseif event.phase == “ended” or event.phase == “cancelled” then
— we end the movement by removing the focus from the object
display.getCurrentStage():setFocus( self, nil )
self.isFocus = false
end

end

— return true so Corona knows that the touch event was handled properly
return true
end

— finally, add an event listener to our square to allow it to be dragged
square:addEventListener( “touch”, square )

In part 2 of building circle pop with Corona SDK, we will create the game scene. The game scene will task the player with popping circles. These circles will be randomly positioned with random colors and we’ll even keep track of how many circles they are popping. If you haven’t read part 1, please read part 1 first before continuing with this tutorial.

Open up your project folder, create a new file called scene-game.lua, and open it up in your favorite text editor. Similar to the menu scene, we’ll require in the widget library as well as our positioning variables.

local widget = require( “widget” )

— These values are set for easier access later on.
local acw = display.actualContentWidth
local ach = display.actualContentHeight
local cx = display.contentCenterX
local cy = display.contentCenterY
local bottom = display.viewableContentHeight – display.screenOriginY
We’ll continue with our variable declarations by creating variables for our circles, counter, and player score. I’ve placed comments next to each line so you know what each one is used for.

— The next lines are forward declares
local createCircles, timerForCircles — forward declare for timer
local enemyCircle = {} — a table to store the enemy circles
local enemyCounter = 1 — a counter to store the number of enemies

local playerScore — stores the text object that displays player score
local playerScoreCounter = 0 — a counter to store the players score
Screenshot 2016-07-06 12.59.43

In the menu scene, we have a function that whisks the player to the game scene. In the game scene, we’ll add a function that will send the player back to the menu scene. We’ll also cancel the timer by calling timer.cancel(timerForCircles). This cancellation will stop the circles from being created.

— This is called when the menu button is touched. This will send the player back to the menu.
local function onPlayTouch( event )
if ( “ended” == event.phase ) then
timer.cancel(timerForCircles)
composer.gotoScene(“scene-menu”)
end
end
We’ll also add another function that will respond to the player touch. While I have a comment in the code below, the function onCircleTouch is called when a circle is touched. On the ended phase, the circle is removed, the player gets a point, and the event returns true. The last part is important because it’ll stop the player from touching multiple circles at once.

— This function will remove the circle on touch, increment the player score by 1, and return true. The return true means the function was called successfully.
local function onCircleTouch(event)
if ( “ended” == event.phase ) then
display.remove(event.target)

playerScoreCounter = playerScoreCounter + 1
playerScore.text = “Score: “..playerScoreCounter

return true
end
end
Screenshot 2016-07-06 13.00.32
Within the scene:create function, we’ll add in our background, a bottom bar, and the player score text object. The background will cover the entire screen, the bottom bar is where the menu button will be located at, and the player score will keep track of the player score.

— Create the background
local background = display.newRect(sceneGroup, 0, 0, acw, ach)
background.x = cx
background.y = cy

— Create the black bar at the bottom of the screen
local bottombar = display.newRect(sceneGroup, 0, 0, acw, 54)
bottombar:setFillColor(0)
bottombar.anchorY = 1
bottombar.x = cx
bottombar.y = bottom

— Create a text object to keep track of the player score
playerScore = display.newText(sceneGroup, “Score: “..playerScoreCounter, 0, 0, native.systemFont, 20)
playerScore:setFillColor(0)
playerScore.x = cx
playerScore.y = bottombar.y – 70
Next, we’ll add in a button to allow the player to return to the menu. This button will call the function onPlayTouch.

— Create a button to allow the player to return to the menu
local btn_menu = widget.newButton({
left = 100,
top = 200,
label = “Menu”,
fontSize = 40,
onEvent = onPlayTouch
})
btn_menu.anchorY = 1 — anchorY changes the anchor point of the object. By setting it to 1, the anchor point is at the bottom of the object.
btn_menu.x = cx
btn_menu.y = bottom – 5
sceneGroup:insert(btn_menu)
Screenshot 2016-07-06 13.00.58

Finally, we’ll create a function that will be called by the timer. The function will be creating circles and assigning them to the table enemyCircle. We’ll be randomizing the position and color of the circle to provide some playability to our game. Feel free to swap these out with moles, nails, or any other image object that might be a good fit for this style of game.

— This function will create an enemy circle, assign a random color, assign a random position, and attach the touch event listener. At the end, the enemy counter variable is increased by 1.
createCircles = function()
enemyCircle[enemyCounter] = display.newCircle(sceneGroup, 0, 0, 25)
enemyCircle[enemyCounter]:setFillColor(math.random(1,255)/255, math.random(1,255)/255, math.random(1,255)/255)
enemyCircle[enemyCounter].x = math.random(20, acw-20)
enemyCircle[enemyCounter].y = math.random(20, ach-130)
enemyCircle[enemyCounter]:addEventListener(“touch”, onCircleTouch)

enemyCounter = enemyCounter + 1
end
And the last piece to Circle Pop with Corona SDK is to create the timer! This timer will run every 1000 milliseconds (1 second) and will run forever until canceled. If you’d like to set a hard cap to the timer, change the 0 to a different number.

timerForCircles = timer.performWithDelay(1000, createCircles, 0) — Create timer for circle creation
Thank you so much for reading this tutorial series on building a game with Corona SDK. If you have questions or comments, please leave them in the comments below. Thank you for reading!

When I learn a new language or a new SDK, I find myself learning faster and quicker when I have a project. In this tutorial, I’ll teach you how to build Circle Pop. You can download the final version of the code at gamebuildingtools.com/product/circle-pop-for-corona-sdk/.

Before getting started, you’ll need the following:

The latest version of Corona SDK
A text editor, I like to use Sublime Text
To get started, we will create a new project that’s 400×600. Corona provides an easy way to create new projects so fire up Corona SDK and click on New Project. Set the screen size to 400×600.

Create a new project
Create a new project
Set the width and height to 400×600
Set the width and height to 400×600
With the project set up, we’ll start editing main.lua. Open up main.lua in your favorite text editor and we will hide the status bar and use composer to move to the menu scene. Composer is Corona’s official scene management library and gives us an easy way to create scenes and manage scenes.

— Hide the status bar
display.setStatusBar( display.HiddenStatusBar )

— Go to the menu scene
local composer = require( “composer” )
composer.gotoScene(“scene-menu”)
Next, create a new file in the same project folder and name it scene-menu.lua. This file will contain the menu for our game circle pop. The menu will be simple and consist of a background, a logo, and a play button. I’m keeping the menu simple so you can pick up on the basics first. You need to walk before you can run!

And to make things even easier, we will use Corona’s scene template to create our menu scene. Head on over to https://docs.coronalabs.com/api/library/composer/index.html#scene-template and copy everything from ‘local composer’ to ‘return scene’. Once you have this copied, copy the code over to scene-menu.lua.

The first item we will add to our game template is to require in the widget library. Corona provides this built-in library and allows for you to create UI elements even faster. Add the following line after local scene = composer.newScene():

local widget = require( “widget” )
Next, we’ll create some variables that will make positioning our elements even easier. After the widget library, enter the following code:

— These values are set for easier access later on.
local acw = display.actualContentWidth
local ach = display.actualContentHeight
local cx = display.contentCenterX
local cy = display.contentCenterY
local bottom = display.viewableContentHeight – display.screenOriginY
These variables get the actual content width, actual content height, the center x and y locations, and the bottom most point of the app. Then, we’ll create a function that will respond to the play button. This function is called onPlayTouch and will send the player to the game scene. Here’s the code:

— This function will send the player to the game scene
local function onPlayTouch( event )
if ( “ended” == event.phase ) then
composer.gotoScene(“scene-game”)
end
end
When the player touches the play button, which we will add later, the function onPlayTouch will be called. This function accepts a variable as a parameter and this variable lets us know quite a few things. For our purposes, we want to know when the event is in the ended phase. The ended phase is when the player stops interaction with the button, i.e. remove their finger from the screen, and in this phase, we’ll whisk the player off to the game scene.

If you’ve been following along, your code should look something like this:

Menu Scene
Menu Scene
With our scene setup with variables and a function, we’ll start to add in our background, our logo, and our play button. To keep things simple, Circle Pop does not use any images. Instead, we’ll be using built-in text objects and basic shapes. We’ll add the following pieces of code to the scene:create function.

Within local function scene:create, we want a simple white background to cover up the background. We’ll use display.newRect to make this happen.

— Code here runs when the scene is first created but has not yet appeared on screen
local background = display.newRect(sceneGroup, 0, 0, acw, ach)
background.x = cx
background.y = cy
The function display.newRect accepts the parameters in this order – parent, x location, y location, width, and height. We are sending in sceneGroup first because we want to attach the background object to the menu scene. When we transition to another scene, Corona will know this object belongs to this scene and will appropriately move it off scene or remove it from device memory. The x and y location are set to 0 at the creation of the object and we set the width and height to actual content width and height. We wrap up the object by positioning it on the center of the screen.

Then, we will create the title of the game using display.newText. This function accepts the parameters in this order – parent, string, x location, y location, font name, and font size. After the object is declared, we’ll position the object and set the color of the text to black.

— Create the title
local title = display.newText(sceneGroup, “Circle Pop”, 0, 0, native.systemFont, 72)
title.x = cx
title.y = 100
title:setFillColor(0)
The last object we’ll add is the play button. The play button uses the widget library and will trigger the onPlayTouch function when touched. Here’s the code:

— Create a start playing button. When touched, trigger the onPlayTouch function
local btn_play = widget.newButton({
left = 100,
top = 200,
label = “Start Playing”,
fontSize = 48,
onEvent = onPlayTouch
})
btn_play.x = cx
btn_play.y = cy
sceneGroup:insert(btn_play)
Here’s a screenshot with the code in place:

Screenshot 2016-07-06 11.18.41

Finally, we’ll want to add in another function called composer.removeScene in the function scene:show. This remove scene function will destroy the game scene when the player leaves the game scene. This will make sure the player starts a new game every time the player hits the play button.

Screenshot 2016-07-06 11.18.47

local prevScene = composer.getSceneName( “previous” )
if(prevScene) then
composer.removeScene( prevScene )
end

And that’s it for the first part of creating Circle Pop with Corona SDK! In Part 2, we will create the game scene and allow the player to play the game. If you have questions, comments, or just want to say thanks, please leave your comment below. Thanks for reading and make sure to read Part 2.

In this post, I’ll show you how to build a simple moving clock with Corona SDK. This tutorial uses display objects instead of images to keep things simple. Instead of walking through all of the pieces of code, I’ve listed the full script below. Feel free to drop this into your next project or modify as you see fit.

–Hide status bar from the beginning
display.setStatusBar( display.HiddenStatusBar )

— Set Variables
_W = display.contentWidth; — Get the width of the screen
_H = display.contentHeight; — Get the height of the screen

clockBorder = display.newCircle(_W/2,_H/2,125)
clockBorder:setFillColor(0,0,0)
clockBorder.strokeWidth = 5
clockBorder:setStrokeColor(255,255,255)

hourHand = display.newLine(_W/2,_H/2,_W/2,80)
hourHand.width = 5
hourHand:setColor(0,255,0)

minuteHand = display.newLine(_W/2,_H/2,_W/2,47)
minuteHand.width = 3
minuteHand:setColor(0,50,255)

secondHand = display.newLine(_W/2,_H/2,_W/2,37)
secondHand.width = 2
secondHand:setColor(255,0,0)

local function updateClock(e)
local currentTime = os.date(“*t”)
secondHand.rotation = currentTime.sec * 6
minuteHand.rotation = currentTime.min * 6
hourHand.rotation = currentTime.hour * 30 + (currentTime.min * 0.5)
end

updateClock()
timer.performWithDelay(1000, updateClock, 0)

If you have any particular questions about the code above, please let me know in the comments.

Corona has come a long way in the options that it offers developers for text manipulation. They offer the ability to align text, font sizes, font colors, and more. However, they are missing the option to add drop shadows. In this tutorial, we’ll learn how to create a function that can be used to add drop shadows to text objects.

For those of you that are unfamiliar with a drop shadow, a drop shadow is a visual effect that makes an object look raised and is commonly used on windows, menu items, or in this case, text objects. There are a ton of applications for this effect.

In our tutorial, we will use white text on an orange background. So, we’ll get started by creating a new rectangle that’s orange.

local background = display.newRect(0,0,display.contentWidth,display.contentHeight)
background:setFillColor(255,127,0)
Next, we will create a function called createTextWithShadow so we can use the function in our other apps. When you can, it’s makes sense to keep a list of these functions in a separate file so you can add them to other apps even easier. The parameters for our function is as follows:

mytext = This is the text to be used in our text object.
x = The x location of the text object.
y = The y location of the text object.
fontType = The font you want to use.
fontSize = How big you want the font to be.
shadowOffset = How far away you want the shadow to be.
Within the function, we’ll use these parameters to create two text objects – one for the shadow and one for just the text object.

function createTextWithShadow(mytext, x, y, fontType, fontSize, shadowOffset)
local textobjectshadow = display.newText(mytext,x+shadowOffset,y+shadowOffset,fontType,fontSize)
textobjectshadow:setTextColor(0,0,0,128)

local textobject = display.newText(mytext,x, y, fontType, fontSize)
end
Finally, we will call the function we just wrote with the parameters that we specified.

createTextWithShadow(“Game Building Tools”,35,100, native.systemFont,74,8)
Anytime you call this function, you’ll have a text object with a drop shadow. You can change the color of the drop shadow by changing the numbers in setTextColor(). Additionally, you may want to adjust the offset depending on the size of your object. If you have a larger object, you may need to increase the offset to see the drop shadow.

Below is the code in one snippet in case you want to copy and paste this code into your project. If you have questions for me, please let me know in the comments below!

local background = display.newRect(0,0,display.contentWidth,display.contentHeight)
background:setFillColor(255,127,0)

function createTextWithShadow(mytext, x, y, fontType, fontSize, shadowOffset)
local textobjectshadow = display.newText(mytext,x+shadowOffset,y+shadowOffset,fontType,fontSize)
textobjectshadow:setTextColor(0,0,0,128)

local textobject = display.newText(mytext,x, y, fontType, fontSize)
end

createTextWithShadow(“Thats So Panda”,35,100, native.systemFont,74,8)

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,loadingWidth0.975,loadingHeight0.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!