简体   繁体   English

如何在pygame中找到2点之间的角度?

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

I am writing a game in Python with Pygame. 我正在使用Pygame用Python编写游戏。
The co-ords (of my display window) are (我的显示窗口)的合作伙伴是
( 0 , 0 ) at the top left and 左上角的( 0 , 0 )
(640,480) at the bottom right. (640,480)

The angle is 角度是
when pointing up, 朝上时
90° when pointing to the right. 指向右侧时为90°

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 x1y1是炮塔合作
x2 , y2 are the player co-ords x2y2是玩家合作伙伴
a is the angle's measure a是角度的度量

First, math has a handy atan2(denominator, numerator) function. 首先, math有一个方便的atan2(denominator, numerator)函数。 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. 通常,你使用atan2(dy,dx)但是因为Pygame相对于笛卡尔坐标翻转y轴(如你所知),你需要使dy负,然后避免负角度。 ("dy" just means "the change in y".) (“dy”仅表示“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. degs应该是你正在寻找的。

考虑一个三角形

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. 你可能想要这样的东西 - 你可能需要摆弄一下 - 我可能会偏离180度。 You'll also need to special-case the situation where dy==0, which I didn't do for you. 你还需要特殊情况下dy == 0的情况,我没有为你做。

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; 我的其余代码并不挑剔degs的负值; anyway, it works now and I'd like to say thanks for your help. 无论如何,它现在有效,我想感谢您的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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