繁体   English   中英

如何让pygame sprite组移动?

[英]How to make a pygame sprite group move?

我为我的敌人制作了一个pygame.sprite.group。 我可以在屏幕上显示它们,但我不知道如何让它们全部移动? 我想让他们在平台上来回踱步(如左右不断)。 我知道如何使用一个精灵的动作,但不是一组精灵。

这就是我现在所拥有的:

class Platform(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load('levoneplatform.png')
        self.rect = self.image.get_rect()

class Enemy(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load('enemy.png')
        self.rect = self.image.get_rect()

class LevOne():
    def __init__(self):

        self.background_image = pygame.image.load('night.png').convert_alpha()


        platforms_one = [ (200,300),
                        (50,500),
                        (550,650),
                        (300,200),
                        (120,100)
                   ]
        for k,v in platforms_one:
            platform = Platform()
            enemy = Enemy()
            platform.rect.x = k
            enemy.rect.x = k
            platform.rect.y = v
            enemy.rect.y = v - 44
            platform_list.add(platform)
            enemy_list.add(enemy)

    def update(self):
         screen.blit(self.background_image, [0, 0])

screen = pygame.display.set_mode((800,600))
enemy_list = pygame.sprite.Group()
platform_list = pygame.sprite.Group()

其余的基本上就像我的状态变化和更新。 我不知道如何移动整个精灵组。 我知道如何在一个列表中移动一个精灵,但不是一堆精灵。

我会向你的Enemy类引入2个新属性: dxplatform dx是x方向的当前速度,而平台是敌人所在的平台。 你必须将平台作为参数传递给你的敌人对象,这应该不是问题(只是在创建平台和敌人时传递它)。 你的敌人类现在看起来像这样:

class Enemy(pygame.sprite.Sprite):

    def __init__(self, platform):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load('enemy.png')
        self.rect = self.image.get_rect()
        self.dx = 1  # Or whatever speed you want you enemies to walk in.
        self.platform = platform

由于你的敌人继承了pygame.sprite.Sprite,你可以使用以下内容覆盖update()方法:

class Enemy(pygame.sprite.Sprite):

    def __init__(self, platform):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load('enemy.png')
        self.rect = self.image.get_rect()
        self.dx = 1  # Or whatever speed you want you enemies to walk in.
        self.platform = platform

    def update(self):
        # Makes the enemy move in the x direction.
        self.rect.move(self.dx, 0)

        # If the enemy is outside of the platform, make it go the other way.
        if self.rect.left > self.platform.rect.right or self.rect.right < self.platform.rect.left:
                self.dx *= -1

你现在可以做的就是在游戏循环中调用精灵组enemy_list.update() ,这将调用你所有敌人的更新方法,让他们移动。

我不知道您的项目的其余部分是什么样的,但考虑到您提供的代码,这应该可行。 你以后可以做的是在更新方法中消磨时间,使你的敌人不会根据fps移动,而是按时间移动。 只要该组中的所有对象都具有相同参数的update方法,pygame.sprite.Group.update()方法就会获取任何参数。

有关更多信息,请查看此演讲或阅读pygame文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM