Dragging objects on the screen is not difficult. There are a few steps that need to be followed.
Since a drag must begin on a touch down and end when you touch up. You’ll need to use a touch event, rather than a tap.
Focus describes which object is currently getting the computers attention. The dragging object needs to keep focus for the duration of the drag. If another object takes focus in the middle of the drag our object may stop moving in the middle of a dragging unintentionally.
To make the drag look best we will want the dragged object to move a distance relative to it’s center and the location of the initial touch. Without this offset the object will shift to align it’s center with your finger when the touch begins.
When the drag is finished we need to return focus to the stage. This will allow other objects to take focus.
-- make an object to drag local box = display.newRect( 0, 0, 100, 100 ) box.x = display.contentCenterX -- Move the object to the box.y = display.contentCenterY -- center of the screen -- This function handles touch events on the object local function on_touch( event ) -- Get the target object local target = event.target -- Check the phase of the event. Here the drag begins if event.phase == "began" then -- When the event begins local parent = target.parent -- get the parent object parent:insert( target ) -- move the drag object to the top -- The dragging object needs to keep focus display.getCurrentStage():setFocus( target ) target.isFocus = true -- Mark this object as having focus -- Get the offset from center of the object to the location -- of the event target.offsetX = event.x - target.x target.offsetY = event.y - target.y -- This phase handles moving the object elseif target.isFocus and event.phase == "moved" then target.x = event.x - target.offsetX -- Position the object target.y = event.y - target.offsetY -- using the offsets -- This phase ends the drag elseif event.phase == "ended" or event.phase == "cancelled" then display.getCurrentStage():setFocus( nil ) -- reset focus target.isFocus = false -- mark this object as no longer having focus end end -- Add this event listener for touch events to the dragging object box:addEventListener( "touch", on_touch )
This example was taken from: http://developer.anscamobile.com/content/drag-me. This simplifies the Drag Me example to it’s essential code.