How to move a character based on touch with Corona SDK

Hello and thanks for stopping by! In this tutorial, we are going to learn how to move an object based on a player’s touch. To keep things simple, I’ll be using basic shapes for this tutorial.

Character movement is a fundamental action in different types of games and with Corona SDK, it’s fairly straightforward to implement. When you finish this tutorial, feel free to replace the basic shapes with game characters of your choice. Let’s get started!

First, let’s go ahead and declare our objects that we’ll be using later on. The variables that are declared will be used for the player object and for the background.

local myPlayer, background

Then, we will create the function that responds to the touch event. This tutorial uses Corona’s built-in touch event functionality to trigger this function. Here’s the function:

local function onBackgroundTouch(event)
 if(event.phase == "ended") then
 myPlayer.x = event.x
 myPlayer.y = event.y

The function starts out with onBackgroundTouch(event) and this is creating the function. The word ‘event’ is passed into the function as a parameter and will let us know where the touch event happened and what phase the event is in. Events can be in began, moved, ended, or cancelled phases. In our case, we want to know when the event ended (when the player has lifted their finger from the device) and we capture this in the if/then statement. Finally, we set the myPlayer object to the x/y location of the event.

With out background function set, we need to create a background. I elected for a simple black rectangle that fills up the entire screen and centered it. Anytime the background is touched, the function onBackgroundTouch is triggered.

local background = display.newRect(0,0,display.contentWidth,display.contentHeight)
background.x = display.contentWidth*0.5
background.y = display.contentHeight*0.5
background:addEventListener("touch", onBackgroundTouch)

Finally, we have our player object. For simplicity purposes, I created a circle object and placed it in the top left.

myPlayer = display.newCircle(0,0,25);
myPlayer.x = 100; myPlayer.y = 100;

And that’s it! You can now move objects around the screen! If you’re a pro, you can replace the two lines in the function with the following line: myPlayer, { time=450, x=event.x, y=event.y } ) This is how your function should look:

local function onBackgroundTouch(event)
 if(event.phase == "ended") then myPlayer, { time=450, x=event.x, y=event.y } )

By using a transition instead of snapping the player to the location, you’ll give off a more polished look in your game. Plus, it’s more fun!

Thanks for reading!

Leave a Reply

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