Catch Me – Part 2

In Part 2 of Catch Me, we created the interface and the 3 functions that will be used within this Corona SDK game – createCoin(), player:touch(), and onCollision(). This tutorial will complete each one of these functions and wrap up our mini-game game.

We’ll start with Part 2 by creating the code for the function createCoin(). This function, as the name implies, will create coins in the game. The coins will start at the top of screen and with a physics body attached to the image, the coins will drop towards the bottom of the screen. Each coin is also assigned a random x position to ensure some randomness to our game.

local function createCoin()
 coinsCounter = coinsCounter + 1
 coins[coinsCounter] = display.newImage("images/coin.png", 35, 35)
 coins[coinsCounter].x = math.random(20,300)
 coins[coinsCounter].y = - 40
 coins[coinsCounter].id = "coin"

Next, we have the player:touch() function. In the touch function, we are going to allow our player to drag the image left and right to catch coins. This is different from our previous tutorials where the accelerometer was used instead.

The player:touch() function starts out by looking for the event phase. During the began phase, the focus is set on the object and the initial x position is recorded. In the moved phase, the image object’s x position is updated according to where the player drags his or her finger. The touch function is then wrapped up in the end/cancelled phase by removing focus on the object. It’s important to remove focus on the object so the player can interact with other elements on the screen.

function player:touch( event )
 if event.phase == "began" then
  display.getCurrentStage():setFocus( self, )
  self.isFocus = true
  self.markX = self.x
 elseif self.isFocus then
  if event.phase == "moved" then
   self.x = event.x - event.xStart + self.markX
  elseif event.phase == "ended" or event.phase == "cancelled" then
   display.getCurrentStage():setFocus( self, nil )
   self.isFocus = false
return true -- return true so Corona knows that the touch event was handled properly

Finally, we have our onCollision function. This function will be triggered when a coin object collides with the player. On the collision, the coin object will be removed.

local function onCollision( event )
 if ( event.phase == "began" ) then
  if( == "player" and == "coin") then

And that’s it for our mini-game, Catch Me! You can download the full source pack under Templates in case you got stuck somewhere along the game tutorial. If you have comments or questions, please let me know in the comments below!

Daniel Williams

Leave a Reply

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