Forked from HoraceBury/simple drag and rotate demo.lua
Created
October 7, 2016 08:20
-
-
Save nadar71/020ff5962860acda1dcbf7937e3ad242 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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