Object Movement Based on Touch Events with Corona SDK
Hello and welcome to another Corona SDK tutorial! In this tutorial, I’ll show you to move an object based on a touch event. A touch event could happen when the player uses their finger or stylus to touch a device. When the touch happens, we’ll capture the x and y location of the event and move the object accordingly. Let’s get started!
First, let’s start out by creating two objects for our player and background.
local myPlayer, background
Next, let’s create a function that will be called when the touch event happens. In this function, onBackgroundTouch, the myPlayer object will be moved to the event.x and event.y location. These values are passed in through the parameter via the variable event.
local function onBackgroundTouch(event) if(event.phase == "ended") then myPlayer.x = event.x myPlayer.y = event.y end end
We’ll also need an object to respond to the touch event so we’ll create a background that takes up the entire width and height. When the background object is touched, the function onBackgroundTouch will be called.
local background = display.newRect(0,0,display.contentWidth,display.contentHeight)
background.x = display.contentWidth*0.5
background.y = display.contentHeight*0.5
background:setFillColor(0,0,0)
background:addEventListener("touch", onBackgroundTouch)
Finally, we’ll create a circle object and assign it to the myPlayer variable. This object can be replaced with an image of your choosing.
myPlayer = display.newCircle(0,0,25); myPlayer.x = 100; myPlayer.y = 100;
And that’s it! If you drop this code into your project or create a new one using this code, then you’ll be able to move the circle around the screen. If you want to take this a step further, you can use transition.to() to animation motion in the object. By using transition.to(), the player object will move to the touch location instead of warping there.
local function onBackgroundTouch(event)
if(event.phase == "ended") then
transition.to( myPlayer, { time=450, x=event.x, y=event.y } )
end
end
If you have any questions, please let me know in the comments!