0

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.

khelwood
  • 55,782
  • 14
  • 81
  • 108
FluffyFlounder
  • 140
  • 2
  • 8

2 Answers2

6

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)
Andy
  • 3,132
  • 4
  • 36
  • 68
0

In pygame you can compute the angle between 2 vector by the use of pygame.math.Vector2 objects and angle_to():

In the following example, (x0, y0) is the rotation point. (x1, y1) and (x2, y2) are the 2 points, which define the vectors form (x0, y0):

v1 = pygame.math.Vector2(x1-x0, y1-y0)
v2 = pygame.math.Vector2(x2-x0, y2-y0)
angle = v1.angle_to(v2)

angle_to() calculates the angle to a given vector in degrees.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174