Welcome to another post from That’s So Panda! Today’s post will cover a topic that may seem difficult, but it’s actually really simple: dragging objects in Corona SDK. Dragging objects can be used for a lot of things in games such as shape matching games, top person shooters, puzzle games, and so much more. Before we dive into the code, let’s discuss how we will be accomplishing this.
Inside the touch event listener of an object, we set the focus on the object that is being touched and store the original x and y position of the object. Then, as the player drags their finger (or stylus) around the screen, you subtract the location of the new location from the start location of the event and add the original location. When the player is no longer touching the object, because they have removed their finger from the screen or another interruption has happened, we then remove the focus from the object.
I know this sounds like a lot, but it’s actually pretty easy! Here’s the code in action.
-- hide the status bar, shouldnt this just be on by default? display.setStatusBar(display.HiddenStatusBar) -- create a circle and put it in the center of the screen local circle = display.newCircle( display.contentWidth*0.5,display.contentHeight*0.5, 75) circle:setFillColor( 255 ) -- touch listener function function circle: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 propertly return true end -- finally, add an event listener to our circle to allow it to be dragged circle:addEventListener( "touch", circle )
And that’s it to dragging objects using Corona SDK! I told you it wasn’t that bad. If you have questions or comments, please leave them below!