How to find the angle between two points in pygame?

I am writing a Python game with Pygame.
The coordinates (of my display window) ( 0 , 0 ) in the upper left and
(640,480) bottom right.

The angle is when hovering up,
90° when turning right.

I have a player sprite with a central position, and I want the turret on the gun to point to the player. How to do it?
Let's say
x1 , y1 - tower coordinates
x2 , y2 - player coordinates a - this is a measure of the angle

+4
source share
4 answers

OK, using a combination of your answers and some other websites, I found working code:

 dx,dy = x2-x1,y2-y1 rads = math.atan2(dx/dy) degs = math.degrees(rads) 

The rest of my code is not fussy about the negative degs value; Anyway, it works now, and I would like to say thanks for your help.

-4
source

Firstly, math has a convenient function atan2(denominator, numerator) . Usually you use atan2(dy,dx) , but since Pygame flips the y axis relative to the Cartesian coordinates (as you know), you need to make dy negative and then avoid negative angles. ("dy" simply means "change y".)

 from math import atan2, degrees, pi dx = x2 - x1 dy = y2 - y1 rads = atan2(-dy,dx) rads %= 2*pi degs = degrees(rads) 

degs should be what you are looking for.

+25
source

Given the triangle

 sin(angle)=opposed side / hypotenuse 
+2
source

You probably want something like this - you may need to play a little - I can be 180 degrees. You will also need a special case when dy == 0, which I did not do for you.

 import math # Compute x/y distance (dx, dy) = (x2-x1, y2-y1) # Compute the angle angle = math.atan(float(dx)/float(dy)) # The angle is in radians (-pi/2 to +pi/2). If you want degrees, you need the following line angle *= 180/math.pi # Now you have an angle from -90 to +90. But if the player is below the turret, # you want to flip it if dy < 0: angle += 180 
+1
source

Source: https://habr.com/ru/post/1411013/


All Articles