I made a ‘transposition’ of movieclip.lua’s drag function into a new library. My simple little editing now allows you to add local dragIt=require "dragIt" at the top of your code and use the movieclip function setDrag. It works exactly the same as the movieclip function, only now, instead of saying animation:setDrag{drag, bounds}, now you can add drag to anything (not just a a movieclip animation) by calling, dragIt:setDrag(myObject, {drag, bounds}. Here is the edited version of movieclip’s drag function to put in another library:
PLEASE NOTE:
I did not write this. Credit goes where credit is due. This is by Ansca. I only made some slight changes to set it to be able to drag anything.
local function dragMe(self, event)
local g=event.target
local onPress = self.\_onPress
local onDrag = self.\_onDrag
local onRelease = self.\_onRelease
if event.phase == "began" then
display.getCurrentStage():setFocus( self )
g.\_startX = event.x - g.x
g.\_startY = event.y - g.y
if onPress then
result = onPress( event )
end
elseif event.phase == "moved" then
if transpose == true then
if limitX ~= true then
g.x = g.\_startX - (event.yStart - event.y)
end
if limitY ~= true then
g.y = g.\_startY + (event.xStart - event.x)
end
else
if limitX ~= true then
g.x = event.x - g.\_startX
if (dragBounds) then
if (g.x \< dragLeft) then g.x = dragLeft end
if (g.x \> dragLeft + dragWidth) then g.x = dragLeft + dragWidth end
end
end
if limitY ~= true then
g.y = event.y - g.\_startY
if (dragBounds) then
if (g.y \< dragTop) then g.y = dragTop end
if (g.y \> dragTop + dragHeight) then g.y = dragTop + dragHeight end
end
end
end
if onDrag then
result = onDrag( event )
end
elseif event.phase == "ended" then
display.getCurrentStage():setFocus( nil )
gX=g.x
gY=g.y
if onRelease then
self.y=gY
self.x=gX
result = onRelease( event )
end
end
-- stop touch from falling through to objects underneath
return true
end
function setDrag( item, params )
if ( params ) then
if params.drag == true then
limitX = (params.limitX == true)
limitY = (params.limitY == true)
transpose = (params.transpose == true)
dragBounds = nil
if ( params.onPress and ( type(params.onPress) == "function" ) ) then
item.\_onPress = params.onPress
end
if ( params.onDrag and ( type(params.onDrag) == "function" ) ) then
item.\_onDrag = params.onDrag
end
if ( params.onRelease and ( type(params.onRelease) == "function" ) ) then
item.\_onRelease = params.onRelease
end
if ( params.bounds and ( type(params.bounds) == "table" ) ) then
dragBounds = params.bounds
dragLeft = dragBounds[1]
dragTop = dragBounds[2]
dragWidth = dragBounds[3]
dragHeight = dragBounds[4]
end
item.touch = dragMe
item:addEventListener( "touch", item )
else
item:removeEventListener( "touch", item )
dragBounds = nil
end
end
end
binc [import]uid: 147322 topic_id: 27488 reply_id: 327488[/import]
[import]uid: 52491 topic_id: 27488 reply_id: 112146[/import]