'Python - Calculate angle from object1(as x and y) to object2(as x and y)
Solution 1:[1]
This is a classic use case for the math.atan2 function:
from math import atan2, degrees
def AngleFromObject1ToObject2InDegrees(object1, object2):
return degrees(atan2(object2.y - object1.y, object2.x - object1.x))
Note that this uses the mathematical convention of angles that start at zero along the positive x-axis (to the right), and increase counter-clockwise. If you want 0 to be up and for them to increase clockwise (like the bearings on a magnetic compass's dial), you can swap the arguments to atan2. You also might consider keeping your angle in radians, it's a lot more convenient that way (since other trigonometric functions expect radians).
Solution 2:[2]
The idea is to translate one of the points to the origin, offset the other point by the same distance we offset the point moved to the origin, then convert the second point (not the origin point) to polar coordinates. What this returns is a distance between the origin and the point, as well as, the angle.
import math
# where object1 and object2 are tuples of x, y pairs
def AngleFromObject1ToObject2InDegrees(object1, object2):
translate_to_origin = (object1[0] - 0, object1[1] - 0)
new_points = (object2[0] - translate_to_origin[0], object2[1] - translate_to_origin[1])
return (math.sqrt(new_points[0] ** 2 + new_points[1] ** 2), math.degrees(math.atan(new_points[1] / new_points[0])))
print(AngleFromObject1ToObject2InDegrees((1,1),(5,5)))
print(AngleFromObject1ToObject2InDegrees((5,5),(1,1)))
As a "one liner":
import math
# where object1 and object2 are tuples of x, y pairs
def AngleFromObject1ToObject2InDegrees(object1, object2):
return (math.sqrt((object2[0] - object1[0]) ** 2 + (object2[1] - object1[1]) ** 2), math.degrees(math.atan((object2[1] - object1[1]) / (object2[0] - object1[0]))))
print(AngleFromObject1ToObject2InDegrees((1,1),(5,5)))
print(AngleFromObject1ToObject2InDegrees((5,5),(1,1)))
Solution 3:[3]
Could done by using simple trigonometry, first you calculate the horizontal distance between object1 and object2 i.e x_2 - x_1 and then calculate the vertical distance b/w object1 and object2 i.e y_2 - y_1. The horizontal distance is our base and the vertical distance is our perpendicular.
perpendicular/base = tan(?) now take inverse
atan(perpendicular/base) = ?
A way of implementing this in python will be easy you can use math.atan to achieve your purpose something like
math.atan((y2-y1)/(x2-x1))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 |

