繁体   English   中英

为什么找到两点之间的角度的方法如此不准确?

[英]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.

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