atan2 problem

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
PGUp
Party member
Posts: 105
Joined: Fri Apr 21, 2017 9:17 am

atan2 problem

Post 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
-
User avatar
raidho36
Party member
Posts: 2063
Joined: Mon Jun 17, 2013 12:00 pm

Re: atan2 problem

Post 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.
User avatar
ivan
Party member
Posts: 1911
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

Re: atan2 problem

Post 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
Post Reply

Who is online

Users browsing this forum: No registered users and 185 guests