Page 1 of 1

atan2 problem

Posted: Sat Apr 29, 2017 2:25 am
by PGUp
hi, so i have a problem with atan2, i want to make my rectangle to face mouse and rotate towards it, i try to use atan2, but it didnt work, it shows a very weird movement instead,

(in the update function)
angle = angle + math.atan2(y - love.mouse.getY, love.mouse.getX() - x) * dt
end

the rotation is uncontrollable

Re: atan2 problem

Posted: Sat Apr 29, 2017 2:48 am
by raidho36
That's because you're adding up to rotation angle every frame. What you need to do is to apply it as is.

Re: atan2 problem

Posted: Sat Apr 29, 2017 7:08 am
by ivan
Yes, like raidho said, it should be:

Code: Select all

target_angle = math.atan2(y - love.mouse.getY, love.mouse.getX() - x)
If you're looking for gradual rotation they you need the find the arc between the "current" and "target" angle.

Code: Select all

arc = (current_angle - target_angle + math.pi)%(2*math.pi) - math.pi
Just make sure to check if the "current angle" is near the target to avoid jitter (and division by 0):

Code: Select all

if math.abs(arc) < rotation_speed*dt then
  -- already facing the target!
  return
end
Then you can normalize the arc and use that to rotate at a constant speed:

Code: Select all

direction = arc/math.abs(arc)
current_angle = current_angle + direction*rotation_speed*dt