[Almost working source included] Rotating towards a touch

Im working on a basic topdown shooter and I need the character to be constantly aiming where your finger is (even if you move it). It works fairly well except when you pass 360 or 180 , when you do it flips and stays flipped until you release your touch. 

Example Video:

ed7a4e1dd1ee02a5c21389dad9b3422c.gif

As you see it works fine until I hit 0 or 180 while holding down. I can correct this by releasing my touch and touching again.

Current Source:

local function press(event) if event.phase == "began" then touchX = event.x touchY = event.y local function rotateGun() print(" x: " .. touchX .. " y: " .. touchY) local xDist = touchX-gunner.x ; local yDist = touchY-gunner.y local angleBetween = math.deg( math.atan( yDist/xDist ) ) if ( event.x \< gunner.x ) then angleBetween = angleBetween+90 else angleBetween = angleBetween-90 end local deltaAngle =(angleBetween) - 180 gunner.rotation = deltaAngle print(" g:" .. gunner.rotation .. " t:" .. deltaAngle) end rotateTimer = timer.performWithDelay(10, rotateGun, 0) elseif event.phase == "moved" then touchX = event.x touchY = event.y elseif event.phase == "ended" then timer.cancel(rotateTimer) elseif event.phase == "canceled" then timer.cancel(rotateTimer) end end

gunner is the turret part of the tank and I add the the runtime listener later. Does anyone know why this is happening?

Try this for deltaAngle instead:

local mFloor = math.floor local deltaAngle = mFloor((angleBetween - obj.rotation) + 0.5) deltaAngle = (deltaAngle + 180) % 360 - 180

… Also, it is good practice to correct over-rotations, unless you explicityly want them

if( obj.rotation \< 0 ) then obj.rotation = obj.rotation + 360 end if( obj.rotation \>= 360 ) then obj.rotation = obj.rotation - 360 end

Thank you so much this worked flawlessly with two small tweaks ( Got rid of the -obj,rotation and -180). I was getting so frustrated last night haha 

You’re welcome.  I extracted it from some code of mine where I needed to make the shortest rotation to aim at a target.

Try this for deltaAngle instead:

local mFloor = math.floor local deltaAngle = mFloor((angleBetween - obj.rotation) + 0.5) deltaAngle = (deltaAngle + 180) % 360 - 180

… Also, it is good practice to correct over-rotations, unless you explicityly want them

if( obj.rotation \< 0 ) then obj.rotation = obj.rotation + 360 end if( obj.rotation \>= 360 ) then obj.rotation = obj.rotation - 360 end

Thank you so much this worked flawlessly with two small tweaks ( Got rid of the -obj,rotation and -180). I was getting so frustrated last night haha 

You’re welcome.  I extracted it from some code of mine where I needed to make the shortest rotation to aim at a target.