Pygame 移动多个精灵未按预期工作

Pygame moving multiple sprites not working as expected

我正在 pygame 制作 space 入侵者,我对 python 比较陌生,这是我在 pygame 的第一个项目。我试图让我的外星人在到达屏幕两侧的边缘时向下移动。但是,它并没有按预期工作。我正在将 link 添加到 GitHub 页面,以便任何愿意提供帮助的人都可以查看我的代码。

基本上发生的事情是我将外星人设置为在触摸侧面时向下移动 1 个像素,因为当有很多外星人时,这会将它们向下移动很多。显然,随着外星人开始被杀死,他们向下移动的次数减少了。然而,这不是奇怪的部分。奇怪的是,有时它们会在一侧向下移动 1 px,但在另一侧会向下移动很多。我不太确定我做错了什么。

https://github.com/Kris-Stoltz/space_invaders

我将该代码更改为

    for alien in aliens:
        if alien.rect.right >= WIDTH-1:
            aliens.update()
        elif alien.rect.left <= 1:
            aliens.update()

不过我看看敌人是不是太少了他们不往下移动


def update(self):
    print("x",self.rect.y)
    self.rect.y += 1
    print("y",self.rect.y)
    self.direction *= -1
That peace of code looks like incorrect

添加 break 语句,这样您就不会多次调用更新(如果偶数个外星人撞到墙上,您最终会朝同一个方向行进!) 您也必须增加更新中的 y 提前量:

for alien in aliens:
    if alien.rect.right >= WIDTH:
        aliens.update()
        break
    elif alien.rect.left <= 0:
        aliens.update()
        break

和:

def update(self):
    self.direction *= -1
    self.rect.y += 10

虽然代码看起来很酷!