Corona SDK and other Game Development Tutorials

Move a Character on Screen Based on Touch

Hello and welcome to another Corona SDK tutorial by That’s So Panda! In today’s tutorial, we’ll learn how to move a character around the screen. For simplicity, I used rectangles and squares for this tutorial.

Moving a character around the screen is useful for all sorts of game genres – space shooters, avoid the obstacles, mazes, and more. This tutorial will walk you through the basics of how to use Corona SDK to get an object, or player character, around the screen using touch events. Let’s get started!

First, we’ll need to declare our objects. We’ll declare two variables – one will be for the player object and another will be for the background.

local myPlayer, background

Next, we’ll go ahead and create the function that responds to the touch event. We’ll use Corona’s built-in touch event functionality. The first think you’ll see is ‘local function onBackgroundTouch(event)’. This line starts the function and uses the variable ‘event’ as a parameter. Next, if the event phase is in the ended state (that means the players finger has left the screen and you could do began instead), we’ll move the player object to the event x and y coordinates. It all happens in a few lines:

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

Once we have our background function, we’ll need our background! I created a simple black rectangle that fills up the entire screen and centered it.

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 an 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!

Want to know when more tutorials and That’s So Panda news comes out?
Sign up for our mailing list to find out the latest news. Don’t worry, I hate spam as much as you do.

Leave a Reply