Say you have two coordinates within a range of 0.0 till 1.0. A: (0.12, 0.75) B: (0.43, 0.97) And you want to walk from point A to point B. How would you calculate the angle in python.Where north is 0 and south is 180.
if you want to get it from North then here you go:
def get_angle(x1,y1,x2,y2):
return math.degrees(math.atan2(y2-y1, x2-x1))
This works because
tan(x) = Opposite/Adjacent;
Opposite/Adjacent = (x2-x1)/(y2-y1);
x=atan(x2-x1, y2-y1)
With atan
being the inverse of tan
. And to not just get the orientation, but true direction, we use the atan2
function instead, as that can get use angels from -pi (-180) to +pi (180), whereas atan
can only yield values between -pi/2 (-90) and pi/2 (90).
One gotcha: the argument order for atan2
is the y difference first, so it's atan2(dy, dx)
, not atan2(dx, dy)
.