首页 文章

精灵组中的精灵方法Pygame

提问于
浏览
0

我有点麻烦,我想知道你是否可以帮助我解决它 .

所以我've made a sprite and created an idle animation method which I'米这样调用 __init__ 方法 .

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.attributes = "blah"

        self.idleAnimation()

    def idleAnimation(self):
        self.animationCode = "Works normally I've checked it"

player      = Player()
playerGroup = pygame.sprite.Group()
playerGroup.add(player)
window = pygame.display.set_mode(yaddi-yadda)

while StillLooping:
    window.fill((0, 0, 0))
    playerGroup.update()
    playerGroup.draw(window)
    pygame.display.flip()

但无论出于何种原因,尽管在 __init__ 方法中调用了idleAnimation方法,但它仍未在组内运行 . 如果我稍后在循环中调用它:

while StillLooping:
    player.idleAimation()
    window.fill((0, 0, 0))
    playerGroup.update()
    playerGroup.draw(window)
    pygame.display.flip()

它运行,但不是 . 我无法理解为什么 . 任何想法都会非常感谢!

2 回答

  • 1

    playerGroup.update() 方法不会神奇地调用 idleAnimation() 方法 . 我真的不明白为什么你认为它应该......

    Group.update的文档说这会调用每个sprite的 update() 方法,所以如果你想在每个循环中调用它,你应该将方法重命名为 update() .

  • 1

    当您实例化对象时, __init__ 方法仅被调用一次 . 因此,在创建对象时会调用 idleAnimation() 方法,就是这样 .

    你的组的 update() 方法只会调用你的精灵的 update 方法,所以你需要按照建议重命名 idleAnimation() ,或者添加一个调用它的 update() 方法,这应该更灵活:

    class Player(pygame.sprite.Sprite):
        def __init__(self):
            pygame.sprite.Sprite.__init__(self)
            self.attributes = "blah"
    
            self.idleAnimation() # You can probably get rid of this line
    
        def idleAnimation(self):
            self.animationCode = "Works normally I've checked it"
    
        def update(self):
            '''Will be called on each iteration of the main loop'''
            self.idleAnimation()
    

    您可能无需在初始化程序中调用 idleAnimation() ,因为它将在您的循环中运行 .

相关问题