【问题标题】:Updating Class Variables While Using Sprite Groups使用 Sprite 组时更新类变量
【发布时间】:2020-03-30 12:04:11
【问题描述】:

我先给你看我的代码(在主循环之外):

START_BAT_COUNT = 10
BAT_IMAGE_PATH = os.path.join( 'Sprites', 'Bat_enemy', 'Bat-1.png' )

bat_image = pygame.image.load(BAT_IMAGE_PATH).convert_alpha()
bat_image = pygame.transform.scale(bat_image, (80, 70))


class Bat(pygame.sprite.Sprite):
    def __init__(self, bat_x, bat_y, bat_image, bat_health, bat_immune):
        pygame.sprite.Sprite.__init__(self)
        self.bat_health = bat_health
        self.bat_immune = bat_immune
        self.image = bat_image
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)
        self.rect.topleft = (bat_x, bat_y)
        self.bat_x = bat_x
        self.bat_y = bat_y
    def update(self):
        self.bat_x += 500

all_bats = pygame.sprite.Group()

for i in range(START_BAT_COUNT):
    bat_x = (random.randint(0, 500))
    bat_y = (random.randint(0, 500))
    bat_health = 5
    bat_immune = False

    new_bat = Bat(bat_x, bat_y, bat_image, bat_health, bat_immune)
    all_bats.add(new_bat)

主循环内部:

all_bats.update()
all_bats.draw(display)

在 update() 中,每次读取代码时,我都会将 bat_x 的值增加 500,并且我知道 bat_x 的值会增加,因为我通过打印 bat_x 的值并观察它们的增加来测试这一点。我的问题是,有没有办法增加 bat_x,并让我的球棒真正移动?截至目前,变量增加但蝙蝠没有移动。谢谢

【问题讨论】:

    标签: python function class pygame sprite


    【解决方案1】:

    您的显示器尺寸是多少?如果你在 x 方向上移动蝙蝠 500 像素,那么一旦它开始移动,它就会立即飞离屏幕。此外,您的球棒可能不会移动,因为您没有更新其矩形的位置。

    在行中

        def update(self):
            self.bat_x += 500
    

    试试

        def update(self):
            self.rect.move_ip(500, 0)
    

    move_ip 将矩形移动到原地,每次更新时蝙蝠的 x 坐标增加 500。

    【讨论】:

    • 完美运行!谢谢。另外,移动的500像素只是为了测试蝙蝠是否真的移动了,所以我选择了一个随机数。
    • @Owen Penn 乐于助人。我正在编辑我的答案以在 move_ip 中包含 y=0 运动,因为您需要同时包含 x 和 y 值。
    猜你喜欢
    • 2019-05-02
    • 2019-07-13
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    相关资源
    最近更新 更多