Pygame 对象移动 Slopes/Angles

Pygame Object Movement With Slopes/Angles

我正在尝试创建一个游戏,当玩家点击时,玩家会射击 在点击点的相同路径上的弹丸。到目前为止,我的代码运行良好,除了玩家点击的距离越远,它移动得越快。这是代码:

class Projectile(pygame.sprite.Sprite):
    x2 = 0
    y2 = 0
    slope_x = 0
    slope_y = 0
    attack_location = ()
    slope = 0

    def __init__(self,image):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(image)
        self.rect = self.image.get_rect()
        self.rect.x = 390
        self.rect.y = 289
        self.attack_location = (mouse_x,mouse_y)
        self.mask = pygame.mask.from_surface(self.image)
        self.x2 = self.attack_location[0]
        self.y2 = self.attack_location[1]
        self.slope_y = self.y2 - 300
        self.slope_x = self.x2 - 400

    def update(self):
        self.rect.x += (self.slope_x) / 15
        self.rect.y += (self.slope_y) / 15

我的代码有点草率和简单,但我想知道是否有办法设置速度常数,或者甚至可以使用三角学来计算射弹在某个角度上的运动。

实际上,我已经设法将矢量归一化了,但是弹丸出来的时候好像是从(0,0)出来的,但是角色的位置是(400,300)。我想知道是否有任何方法可以使向量从 (400,300) 开始,或者是否有其他解决方案来解决我原来的问题。谢谢!这是代码:

    def __init__(self,image):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(image)
        self.rect = self.image.get_rect()
        self.rect.x = 0
        self.rect.y = 0
        self.attack_location = (mouse_x,mouse_y)
        self.mask = pygame.mask.from_surface(self.image)
        self.x2 = self.attack_location[0]
        self.y2 = self.attack_location[1]
        self.d = math.sqrt(((self.x2)**2) + ((self.y2)**2))
        self.slope_x = self.x2 / self.d
        self.slope_y = self.y2 / self.d

    def update(self):
        self.rect.x += (self.slope_x) * 10
        self.rect.y += (self.slope_y) * 10​

您必须对方向向量进行归一化。 像这样:

d = math.sqrt(mouse_x * mouse_x + mouse_y * mouse_y)
self.slope_x = mouse_x / d - 300
self.slope_y = mouse_y / d - 400