Search code examples
pythonpython-3.xmathpygameangle

How to calculate the angle between two points in Python 3?


I want to calculate the angle between two points. For example, say I was making a game and I wanted a gun to point at the mouse cursor, I get the angle it needs to rotate the rotate the gun to that angle.


Solution

  • Using the math library's atan2 function,

    p1 = (2,2)
    p2 = (-1,5)
    
    # Difference in x coordinates
    dx = p2[0] - p1[0]
    
    # Difference in y coordinates
    dy = p2[1] - p1[1]
    
    # Angle between p1 and p2 in radians
    theta = math.atan2(dy, dx)