The tangent of the angle between two points is defined as delta y / delta x That is (y2 - y1)/(x2-x1). This means that math.atan2(dy, dx) give the angle between the two points assuming that you know the base axis that defines the co-ordinates.

Your gun is assumed to be the (0, 0) point of the axes in order to calculate the angle in radians. Once you have that angle, then you can use the angle for the remainder of your calculations.

Note that since the angle is in radians, you need to use the math.pi instead of 180 degrees within your code. Also your test for more than 360 degrees (2*math.pi) is not needed. The test for negative (< 0) is incorrect as you then force it to 0, which forces the target to be on the x axis in the positive direction.

Your code to calculate the angle between the gun and the target is thus

myradians = math.atan2(targetY-gunY, targetX-gunX)

If you want to convert radians to degrees

mydegrees = math.degrees(myradians)

To convert from degrees to radians

myradians = math.radians(mydegrees)

Python ATAN2

The Python ATAN2 function is one of the Python Math function which is used to returns the angle (in radians) from the X -Axis to the specified point (y, x).

math.atan2()

Definition Returns the tangent(y,x) in radius.

Syntax
math.atan2(y,x)

Parameters
y,x=numbers

Examples
The return is:

>>> import math  
>>> math.atan2(88,34)  
1.202100424136847  
>>>
Answer from sabbahillel on Stack Overflow
Top answer
1 of 7
75

The tangent of the angle between two points is defined as delta y / delta x That is (y2 - y1)/(x2-x1). This means that math.atan2(dy, dx) give the angle between the two points assuming that you know the base axis that defines the co-ordinates.

Your gun is assumed to be the (0, 0) point of the axes in order to calculate the angle in radians. Once you have that angle, then you can use the angle for the remainder of your calculations.

Note that since the angle is in radians, you need to use the math.pi instead of 180 degrees within your code. Also your test for more than 360 degrees (2*math.pi) is not needed. The test for negative (< 0) is incorrect as you then force it to 0, which forces the target to be on the x axis in the positive direction.

Your code to calculate the angle between the gun and the target is thus

myradians = math.atan2(targetY-gunY, targetX-gunX)

If you want to convert radians to degrees

mydegrees = math.degrees(myradians)

To convert from degrees to radians

myradians = math.radians(mydegrees)

Python ATAN2

The Python ATAN2 function is one of the Python Math function which is used to returns the angle (in radians) from the X -Axis to the specified point (y, x).

math.atan2()

Definition Returns the tangent(y,x) in radius.

Syntax
math.atan2(y,x)

Parameters
y,x=numbers

Examples
The return is:

>>> import math  
>>> math.atan2(88,34)  
1.202100424136847  
>>>
2 of 7
9

In general, the angle of a vector (x, y) can be calculated by math.atan2(y, x). The vector can be defined by 2 points (x1, y1) and (x2, y2) on a line. Therefore the angle of the line is math.atan2(y2-y1, x2-x1). Be aware that the y-axis needs to be reversed (-y respectively y1-y2) because the y-axis is generally pointing up but in the PyGame coordinate system the y-axis is pointing down. The unit of the angle in the Python math module is Radian, but the unit of the angle in PyGame functions like pygame.transform.rotate() is Degree. Hence the angle has to be converted from Radians to Degrees by math.degrees:

import math

def angle_of_vector(x, y):
    return math.degrees(math.atan2(-y, x))

def angle_of_line(x1, y1, x2, y2):
    return math.degrees(math.atan2(-(y2-y1), x2-x1))

This can be simplified by using the angle_to method of the pygame.math.Vector2 object. This method computes the angle between 2 vectors in the PyGame coordinate system in degrees. Therefore it is not necessary to reverse the y-axis and convert from radians to degrees. Just calculate the angle between the vector and (1, 0):

def angle_of_vector(x, y):
    return pygame.math.Vector2(x, y).angle_to((1, 0))

def angle_of_line(x1, y1, x2, y2):
    return angle_of_vector(x2-x1, y2-y1)

Minimale example:

import pygame
import math

def angle_of_vector(x, y):
    #return math.degrees(math.atan2(-y, x))            # 1: with math.atan
    return pygame.math.Vector2(x, y).angle_to((1, 0))  # 2: with pygame.math.Vector2.angle_to
    
def angle_of_line(x1, y1, x2, y2):
    #return math.degrees(math.atan2(-y1-y2, x2-x1))    # 1: math.atan
    return angle_of_vector(x2-x1, y2-y1)               # 2: pygame.math.Vector2.angle_to
    
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 50)

angle = 0
radius = 150
vec = (radius, 0)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    cpt = window.get_rect().center
    pt = cpt[0] + vec[0], cpt[1] + vec[1]
    angle = angle_of_vector(*vec)

    window.fill((255, 255, 255))
    pygame.draw.circle(window, (0, 0, 0), cpt, radius, 1)
    pygame.draw.line(window, (0, 255, 0), cpt, (cpt[0] + radius, cpt[1]), 3)
    pygame.draw.line(window, (255, 0, 0), cpt, pt, 3)
    text_surf = font.render(str(round(angle/5)*5) + "°", True, (255, 0, 0))
    text_surf.set_alpha(127)
    window.blit(text_surf, text_surf.get_rect(bottomleft = (cpt[0]+20, cpt[1]-20)))
    pygame.display.flip()

    angle = (angle + 1) % 360
    vec = radius * math.cos(angle*math.pi/180), radius * -math.sin(angle*math.pi/180)

pygame.quit()
exit()

angle_to can be used to calculate the angle between 2 vectors or lines:

def angle_between_vectors(x1, y1, x2, y2):
    return pygame.math.Vector2(x1, y1).angle_to((x2, y2))

Minimal example:

import pygame
import math

def angle_between_vectors(x1, y1, x2, y2):
    return pygame.math.Vector2(x1, y1).angle_to((x2, y2))

def angle_of_vector(x, y):
    return pygame.math.Vector2(x, y).angle_to((1, 0))    
    
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 50)

angle = 0
radius = 150
vec1 = (radius, 0)
vec2 = (radius, 0)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    cpt = window.get_rect().center
    pt1 = cpt[0] + vec1[0], cpt[1] + vec1[1]
    pt2 = cpt[0] + vec2[0], cpt[1] + vec2[1]
    angle = angle_between_vectors(*vec2, *vec1)

    window.fill((255, 255, 255))
    pygame.draw.circle(window, (0, 0, 0), cpt, radius, 1)
    pygame.draw.line(window, (0, 255, 0), cpt, pt1, 3)
    pygame.draw.line(window, (255, 0, 0), cpt, pt2, 3)
    text_surf = font.render(str(round(angle/5)*5) + "°", True, (255, 0, 0))
    text_surf.set_alpha(127)
    window.blit(text_surf, text_surf.get_rect(bottomleft = (cpt[0]+20, cpt[1]-20)))
    pygame.display.flip()

    angle1 = (angle_of_vector(*vec1) + 1/3) % 360
    vec1 = radius * math.cos(angle1*math.pi/180), radius * -math.sin(angle1*math.pi/180)
    angle2 = (angle_of_vector(*vec2) + 1) % 360
    vec2 = radius * math.cos(angle2*math.pi/180), radius * -math.sin(angle2*math.pi/180)

pygame.quit()
exit()
Discussions

mathematics - Pygame : problem with calculating an angle between two points - Game Development Stack Exchange
I've been struggling to calculate the angle alpha between an object and a certain point M so that I can move that object to M. To calculate alpha, I'm using trigonometry and more precisely the atan2 function from the python math module : More on gamedev.stackexchange.com
🌐 gamedev.stackexchange.com
September 5, 2021
python - Calculate angle (clockwise) between two points - Stack Overflow
I have been not using math for a long time and this should be a simple problem to solve. Suppose I have two points A: (1, 0) and B: (1, -1). I want to use a program (Python or whatever programming More on stackoverflow.com
🌐 stackoverflow.com
How to calculate the angle between two points in Python 3? - Stack Overflow
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... More on stackoverflow.com
🌐 stackoverflow.com
Calculate angle between two coordinates
This is probably not quite right as the earth is obiously a globe. But here is how you would calculate the angle of two vectors on a plane. If you replace lat with y and lon with x you should see how it all relates. delta_lon = c2.lon - c1.lon delta_lat = c2.lat - c1.lat tan_theta = delta_lon / delta_lat angle_relative_to_true_north = 90 - math.atan(tan_theta) More on reddit.com
🌐 r/learnpython
10
1
June 13, 2021
🌐
Stack Exchange
gamedev.stackexchange.com › questions › 196640 › pygame-problem-with-calculating-an-angle-between-two-points
mathematics - Pygame : problem with calculating an angle between two points - Game Development Stack Exchange
September 5, 2021 - I've been struggling to calculate the angle alpha between an object and a certain point M so that I can move that object to M. To calculate alpha, I'm using trigonometry and more precisely the atan2 function from the python math module :
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-compute-the-angle-between-vectors-using-python
How to Compute the Angle Between Vectors Using Python - GeeksforGeeks
July 10, 2024 - Angle between vectors (in radians): 1.3078015951139772 Angle between vectors (in degrees): 74.9315118405078 · For 3-dimensional vectors, the cross product can also be used to find the angle. The magnitude of the cross product of two vectors
🌐
YouTube
youtube.com › watch
Finding Angle and distance between two points in Python - YouTube
This tutorial shows how to correctly find angle between two points irrespective of the location of points using atan2 function in Python. It also shows how t...
Published   October 10, 2020
🌐
Finxter
blog.finxter.com › home › learn python blog › how to calculate the angle clockwise between two points
How to Calculate the Angle Clockwise Between Two Points - Be on the Right Side of Change
January 19, 2021 - As you can see printing the angle_between(A,B) and angle_between(B,A) gives us two totality different answers! The reason for this is because the first point is moving clockwise to the second point giving us the smaller number. By going counter clockwise, we get a much larger number than the actual angle we are looking for! As you see, writing this program in Python was easy because Python has built in math and NumPy modules to make the code beautiful and clean.
Find elsewhere
🌐
Medium
medium.com › @heyamit10 › calculating-the-angle-between-two-vectors-using-numpy-17e64256601c
Calculating the Angle Between Two Vectors Using NumPy | by Hey Amit | Medium
March 6, 2025 - import numpy as np # Define multiple vector pairs A = np.array([[1, 2], [3, 4], [5, 6]]) B = np.array([[2, 3], [4, 5], [6, 7]]) # Calculate dot products and magnitudes dot_products = np.einsum('ij,ij->i', A, B) magnitudes_A = np.linalg.norm(A, axis=1) magnitudes_B = np.linalg.norm(B, axis=1) # Calculate angles angles_radians = np.arccos(dot_products / (magnitudes_A * magnitudes_B)) angles_degrees = np.degrees(angles_radians) print(f"Angles between vector pairs: {angles_degrees}") ... We calculate magnitudes along the correct axis. The rest is the same — just vectorized! ... Ah, the dreaded nan. It usually pops up because of two things:
Top answer
1 of 8
41

Numpy's arctan2(y, x) will compute the counterclockwise angle (a value in radians between -π and π) between the origin and the point (x, y).

You could do this for your points A and B, then subtract the second angle from the first to get the signed clockwise angular difference. This difference will be between -2π and 2π, so in order to get a positive angle between 0 and 2π you could then take the modulo against 2π. Finally you can convert radians to degrees using np.rad2deg.

import numpy as np

def angle_between(p1, p2):
    ang1 = np.arctan2(*p1[::-1])
    ang2 = np.arctan2(*p2[::-1])
    return np.rad2deg((ang1 - ang2) % (2 * np.pi))

For example:

A = (1, 0)
B = (1, -1)

print(angle_between(A, B))
# 45.

print(angle_between(B, A))
# 315.

If you don't want to use numpy, you could use math.atan2 in place of np.arctan2, and use math.degrees (or just multiply by 180 / math.pi) in order to convert from radians to degrees. One advantage of the numpy version is that you can also pass two (2, ...) arrays for p1 and p2 in order to compute the angles between multiple pairs of points in a vectorized way.

2 of 8
17

Use the inner product and the determinant of the two vectors. This is really what you should understand if you want to understand how this works. You'll need to know/read about vector math to understand.

See: https://en.wikipedia.org/wiki/Dot_product and https://en.wikipedia.org/wiki/Determinant

from math import acos
from math import sqrt
from math import pi

def length(v):
    return sqrt(v[0]**2+v[1]**2)
def dot_product(v,w):
   return v[0]*w[0]+v[1]*w[1]
def determinant(v,w):
   return v[0]*w[1]-v[1]*w[0]
def inner_angle(v,w):
   cosx=dot_product(v,w)/(length(v)*length(w))
   rad=acos(cosx) # in radians
   return rad*180/pi # returns degrees
def angle_clockwise(A, B):
    inner=inner_angle(A,B)
    det = determinant(A,B)
    if det<0: #this is a property of the det. If the det < 0 then B is clockwise of A
        return inner
    else: # if the det > 0 then A is immediately clockwise of B
        return 360-inner

In the determinant computation, you're concatenating the two vectors to form a 2 x 2 matrix, for which you're computing the determinant.

🌐
Reddit
reddit.com › r/learnpython › calculate angle between two coordinates
Calculate angle between two coordinates : r/learnpython
June 13, 2021 - They have JavaScript and Excel ... it for python shouldn't be too difficult. Some keywords that will help you find what you are looking for: "bearing" - the angle on the compass or map from one point to another. "Great circle" - the shortest path along the Earth's surface between two ...
🌐
Forum
forum.cogsci.nl › discussion › 3076 › determining-the-angle-between-three-points
Determining the angle between three points. — Forum
May 9, 2017 - might also be useful: https://docs.python.org/2/library/math.html ... I'm getting the position of point 2 via a mouse.get_click() function, which I think stores it as a tuple. I then unpack the tuple into the separate xpos and ypos to do other stuff with them in the script, but I could in principle still use it. I'm not married to this particular approach, I just grabbed the first function I found on the internet that was seemingly intended to compute angles because I wasn't sure where to begin.
🌐
Statology
statology.org › home › how to compute the angle between vectors using python
How to Compute the Angle Between Vectors Using Python
July 20, 2024 - Third Set Of Vectors: Here, the vectors lie on the same line but point in opposite directions, creating an angle of 180 degrees, the maximum angle possible between two vectors.
🌐
Medium
manivannan-ai.medium.com › find-the-angle-between-three-points-from-2d-using-python-348c513e2cd
Find the Angle between three points from 2D using python | by Manivannan Murugavel | Medium
March 25, 2019 - Now that formula, I will use for finding the angle between three points. We have use multiple dimentional data like 1D, 2D, 3D and higher dimensions not only 2D. But i explained with 2D data points. The dot product may be defined algebraically or geometrically. The geometric definition is based on the notions of angle and distance (magnitude of vectors). The equivalence of these two definitions relies on having a Cartesian coordinate system for Euclidean space.
Top answer
1 of 1
3

PointGeometry doesn't have have a direct method to return the vertical angle between two points, but it can by used in a Python script to deliver what you're after. This example is verbose to demonstrate the calculations in some detail. It could be streamlined and error trapping added for when the vertical distance is zero (i.e. vertical angle = 90 degrees) and test if the points are coincident.

This was tested in ArcMap but should work the same in ArcGIS Pro.

import arcpy
import math

# making the assumption that the points are in a projected coordinate system and
# that the measurement unit for horizontal and vertical are the same i.e. metres

# input feature layer must be points (Z-enabled) and only the first two will be used
# this code could be modified to process all points in a feature layer 
# if required (i.e. turn this into a function)
points = arcpy.GetParameterAsText(0)

# read in the point geometries into a list to make it easier for processing
pointGeometry = []
with arcpy.da.SearchCursor(points, ["SHAPE@"]) as aRows:
    for aRow in aRows:
        pointGeometry.append(aRow[0])

# create variables for the two points
point1 = pointGeometry[0]
point2 = pointGeometry[1]

# get the distance between the points     
horDistance = point1.angleAndDistanceTo(point2, "PLANAR")[1]

# calculate the vertical distance between the points
verDistance = point2.firstPoint.Z - point1.firstPoint.Z

# calculate the vertical angle
angle = math.acos(verDistance/horDistance) # the result is in radians
angleDeg = math.degrees(angle) # convert the angle to degrees

# output the results
arcpy.AddMessage("Horizontal distance Point 1 to 2: {}".format(horDistance))
arcpy.AddMessage("Vertical distance Point 1 to 2: {}".format(verDistance))
arcpy.AddMessage("Vertical angle (radians) Point 1 to 2: {}".format(angle))
arcpy.AddMessage("Vertical angle (degrees) Point 1 to 2: {}".format(angleDeg))

Example output:

🌐
Python Forum
python-forum.io › thread-14188.html
finding angle between three points on a 2d graph
So, i've been trying to find this out for such a long time. So say I have three points A, B, C. Each with X and Y values. ax = 1 ay = 5 bx = 1 by = 2 cx = 5 cy = 1 which looks something like this on a
Top answer
1 of 1
2

I guess that when you ask the angle between vertices, you mean the angle between the two vectors, starting from the origin and going to the two vertice. Those Vectors are actually the coordinate of the vertice but I prefer to be clear to avoid misunderstanding since the angle between two points dont realy make sense.

So it is actually very easy to obtain an angle between two vectors, you can use the Blender implementation of vectors to do that:

mathutils.Vector((v0.x,v0.y,v0.z)).angle(mathutils.Vector((v1.x,v1.y,v1.z)))

(I usually prefer to work with noramlized() vector but I dont think it is necessary for Vector.angle()

BUT: if you want to compute the angle of the two vertice from the center of the sphere, then you need a vector starting from the center and going to each Vertice

You can do something like vector0 = vertice0.co - sphere.location to find this vector.

Keep in mind that if the object has some transformations, location, rotation and scale, you'll need to calculate the world vertice position. You can take a look there for this point

If you want to have a perfect mach of the two vertices when they dont have the same z coordinate, you'll need to rotate around a precies vector and not only the z axis. This vector can be find with a cross product that will give you a vector perpendicular to two other verctors. Your vectors do needs to be normalized in this case

axis = vector0.normalized().cross(vector1.normalized())

If you want tho obtain the angle so that the the rotation on the z axis will align the vertices, except in the z axis, you should compute the rotation on vectors based on a projection of the vertices on a plane with a z normal. To keep it simple in your case, you can juste set the z value to 0 for each vector then normalize them.

Tell me if you need some clarifications on some points.

🌐
analyticslink01
analytics-link.com › post › 2018 › 08 › 21 › calculating-the-compass-direction-between-two-points-in-python
Calculating the compass direction between two points in Python
January 5, 2022 - ... math.atan2 is a function that returns the arc tangent of two numbers x and y. Think back to trigonometry at high school and you might remeber working out the tan(opposite/adjacent) to find the angle between them.
🌐
Blender Artists
blenderartists.org › coding › python support
rotation to match angle between 2 points? - Python Support - Blender Artists Community
August 16, 2011 - Hi all, I need to calculate the “angle” of two points and convert that into a rotation. A picture best explains this: http://www.pasteall.org/pic/show.php?id=16482 In the first example, i need to get the angle between the two points (spline points in this case), and then rotate an object that has been placed at the fist point, so that it is aimed at the second point.