[英]Why is this way of finding the angle between two points so inaccurate?
我正在嘗試使一個精靈與其他人使用角度相交。 這是我使用的功能,可在網上找到:
def findAngle(x,y,x2,y2):
deltaX = x2 - x
deltaY = y2 - y
return math.atan2(deltaY,deltaX)
但是,這是非常不准確的。 當兩個精靈位於相同的X左右時,它們彼此之間通常通常仍相距100-200像素。
這是我的整個程序供您自己運行。
import pygame
import math
screen_size = screen_width,screen_height = 700,500
screen = pygame.display.set_mode(screen_size)
clock = pygame.time.Clock()
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
RED = ( 255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
class Sprite(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
class Particle(Sprite):
def __init__(self,x,y,size):
self.image = pygame.Surface((size,size))
self.rect = pygame.Rect(x,y,size,size)
self.angle = 0
self.speed = 0
def draw(self):
self.rect.x -= math.cos(self.angle) * self.speed
self.rect.y -= math.sin(self.angle) * self.speed
pygame.draw.circle(screen, BLACK, (self.rect.x,self.rect.y), self.rect.width)
def findAngle(x,y,x2,y2):
deltaX = x2 - x
deltaY = y2 - y
return math.atan2(deltaY,deltaX)
class main:
p1 = Particle(100,100,16)
p2 = Particle(600,400,5)
p2.angle = findAngle(100,100,600,400)
p2.speed = 2
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
if event.key == pygame.K_r:
pass
pygame.display.init()
screen.fill(WHITE)
p1.draw()
p2.draw()
pygame.display.flip()
clock.tick(60)
pygame.display.quit()
pygame.quit()
您應該將cos
用作x坐標,將sin
用作y坐標。 您可以在draw
函數中將其向后移動。
P1為100,100,固定P2為600,400,並且以〜30度的角度(或更准確地說,為-120度)移動,因為您正在執行-=而不是+ =。
如果交換cos和sin,每幀p2在X方向上移動-1.715單位,在Y方向上移動-1.02單位。 在Y方向上移動了300個單位(完成后)后,它應該在X方向上移動了500個單位,這就是您要尋找的。
簡化使用pygame內容的步驟:
import math
def findAngle(x,y,x2,y2):
return math.atan2(y2-y,x2-x)
x = 600
y = 400
angle = findAngle(100,100,x,y)
dx = 2 * math.cos(angle)
dy = 2 * math.sin(angle)
while x > 100:
x -= dx
y -= dy
print "At end, we were at %f,%f"%(x,y)
打印出來: 最后,我們在99.224131,99.534479
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.