Dragging objects is something that’s common across many games and apps, but unfortunately, how to do it isn’t readily apparent. Today, I’m going to show you exactly how basic dragging is accomplished—and it’s easier than you think.
Here’s the logic behind it:
At the start of a user’s touch (also known as the “began” phase of a touch event), you must store the current location of the object. Then, during the “move” phase of the event, you subtract the start location of the event (event.xStart, event.yStart) from the event’s current location (event.x, event.y) and also add the stored location of the object. Finally, you change the object’s location to the newly calculated one and that’s what moves the object with the user’s finger.
Sounds like a mouthful right? Here’s the code:
And that’s it! That’s all there is to dragging objects in Corona. And although this tutorial was a little on the short side, its usefulness is infinite—I find myself using the same code I shared here across many different projects.
Feel free to ask any questions you have in the comments section, or start a new thread in the forums and post a link to it.