Skip to content

Instantly share code, notes, and snippets.

@HoraceBury
Last active October 7, 2016 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save HoraceBury/456df98c1dbc4ba7a6966d0b937e6204 to your computer and use it in GitHub Desktop.
Save HoraceBury/456df98c1dbc4ba7a6966d0b937e6204 to your computer and use it in GitHub Desktop.
This code was an answer to a forum question asking for a touch to drag an object but a tap-touch to rotate the object. I kept it simple and without reference to my mathlib.lua for the sake of brevity.
local function angleOnTarget( e )
local a = math.atan2( e.y-e.target.y, e.x-e.target.x ) * 180 / (4*math.atan(1))
if (a<0) then a=a+360 end
return a
end
local function tap(e)
e.target.touchMode = "drag"
print("drag mode")
e.target.dragtimer = timer.performWithDelay( 400, function()
e.target.touchMode = "move"
print("move mode")
end )
return true
end
local function touch(e)
if (e.phase == "began") then
e.target.hasFocus = true
display.currentStage:setFocus( e.target )
e.target.touchMode = e.target.touchMode or "move"
e.target.prev = e
if (e.target.dragtimer) then
timer.cancel( e.target.dragtimer )
e.target.dragtimer = nil
end
e.target.prevangle = angleOnTarget( e )
return true
elseif (e.target.hasFocus) then
if (e.phase == "moved") then
if (e.target.touchMode == "move") then
e.target.x, e.target.y = e.target.x+(e.x-e.target.prev.x), e.target.y+(e.y-e.target.prev.y)
else
local angle = angleOnTarget( e )
e.target.rotation = e.target.rotation + (angle - e.target.prevangle)
e.target.prevangle = angle
end
e.target.prev = e
else
e.target.hasFocus = nil
e.target.prev = nil
display.currentStage:setFocus( nil )
e.target.touchMode = "move"
e.target.prevangle = nil
end
return true
end
return false
end
local rect = display.newRect( display.contentCenterX, display.contentCenterY, 300, 150 )
rect:addEventListener( "touch", touch )
rect:addEventListener( "tap", tap )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment