试图在 pygame 中移动精灵

Trying to move a sprite in pygame

我正在尝试让子弹在 Pygame 中移动。抱歉,如果它有一个简单的修复,我现在想不出来。

这就是我 运行 当我检测到“1”按钮被按下时所做的。

 if pygame.event.get().type == KEYDOWN and e.key == K_1:
    bullet = Bullet()
    bullet.rect.x = player.rect.x
    bullet.rect.y = player.rect.y
    entities.add(bullet)
    bullet_list.add(bullet)
    bullet.update()

...这是真正的项目符号 class。间距有点小

class Bullet(pygame.sprite.Sprite):
    def __init__(self):
         super(Bullet, self).__init__()
         self.image = pygame.Surface([4, 10])
         self.image.fill(pygame.Color(255, 255, 255))
         self.isMoving = False
         self.rect = self.image.get_rect()

    def update(self):
       for i in range(20):
          self.rect.x += 3

我了解更新方法是即时发生的,而不是我想要的较慢的移动。我应该如何让子弹移动得更慢? 我看到的所有答案都涉及完全停止程序,而不是仅仅停止一个对象。有解决办法吗?

您需要在每个游戏刻更新所有子弹,而不仅仅是在玩家按下按钮时。

因此,您需要这样的事件循环:

clock = pygame.time.Clock()
while True:
    clock.tick(60)
    for event in pygame.event.get():
        if event == KEYDOWN and event.key == K_1:
            bullet = Bullet()
            bullet.rect.x = player.rect.x
            bullet.rect.y = player.rect.y
            entities.add(bullet)
            bullet_list.add(bullet)
    for bullet in bullet_list:
        bullet.update()

然后,修改 Bullet class 以执行增量移动,如下所示:

class Bullet(pygame.sprite.Sprite):
    def __init__(self):
         super(Bullet, self).__init__()
         self.image = pygame.Surface([4, 10])
         self.image.fill(pygame.Color(255, 255, 255))
         self.isMoving = False
         self.rect = self.image.get_rect()

    def update(self):
       self.rect.x += 3