简体   繁体   中英

How do I find the angle between 2 points in pygame?

I am writing a game in Python with Pygame.
The co-ords (of my display window) are
( 0 , 0 ) at the top left and
(640,480) at the bottom right.

The angle is
when pointing up,
90° when pointing to the right.

I have a player sprite with a centre position and I want the turret on a gun to point towards the player. How do I do it?
Say,
x1 , y1 are the turret co-ords
x2 , y2 are the player co-ords
a is the angle's measure

First, math has a handy atan2(denominator, numerator) function. Normally, you'd use atan2(dy,dx) but because Pygame flips the y-axis relative to Cartesian coordinates (as you know), you'll need to make dy negative and then avoid negative angles. ("dy" just means "the change in y".)

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

degs ought to be what you're looking for.

考虑一个三角形

sin(angle)=opposed side / hypotenuse

You'll probably want something like this - you may need to fiddle a bit - I may be off by 180 degrees. You'll also need to special-case the situation where dy==0, which I didn't 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

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

dx,dy = x2-x1,y2-y1

rads = math.atan2(dx/dy)
degs = math.degrees(rads)

The rest of my code isn't fussy about a negative value of degs; anyway, it works now and I'd like to say thanks for your help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM