簡體   English   中英

如何在pygame中找到2點之間的角度?

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

我正在使用Pygame用Python編寫游戲。
(我的顯示窗口)的合作伙伴是
左上角的( 0 , 0 )
(640,480)

角度是
朝上時
指向右側時為90°

我有一個中心位置的玩家精靈,我希望槍上的炮塔指向玩家。 我該怎么做?
說,
x1y1是炮塔合作
x2y2是玩家合作伙伴
a是角度的度量

首先, math有一個方便的atan2(denominator, numerator)函數。 通常,你使用atan2(dy,dx)但是因為Pygame相對於笛卡爾坐標翻轉y軸(如你所知),你需要使dy負,然后避免負角度。 (“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應該是你正在尋找的。

考慮一個三角形

sin(angle)=opposed side / hypotenuse

你可能想要這樣的東西 - 你可能需要擺弄一下 - 我可能會偏離180度。 你還需要特殊情況下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

好的,結合您的答案和其他一些網站,我找到了工作代碼:

dx,dy = x2-x1,y2-y1

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

我的其余代碼並不挑剔degs的負值; 無論如何,它現在有效,我想感謝您的幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM