【问题标题】:Pygame Object Movement With Slopes/AnglesPygame 对象运动与斜率/角度
【发布时间】:2015-04-10 01:53:57
【问题描述】:

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

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​

【问题讨论】:

  • 当您点击更远的x2, y2 时,会变大(或变小)。这意味着slope_y, slope_x 变得更大。这意味着您增加rect.x, rect.y 的增量更大。因此,无论何时您更新导弹位置,它都会根据您单击的位置而增加或减少。
  • 我明白,我只是想知道是否有任何方法可以防止这种情况发生。不过还是谢谢。

标签: python pygame sprite angle


【解决方案1】:

你必须规范化方向向量。 像这样的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    相关资源
    最近更新 更多