【问题标题】:Sprite Methods in Sprite Groups Pygame精灵组中的精灵方法 Pygame
【发布时间】:2013-07-14 11:54:17
【问题描述】:

我遇到了一点麻烦,我想知道你是否可以帮我解决它。

所以我制作了一个精灵并创建了一个空闲动画方法,我正在像这样在__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()

它运行但不运行。我不知道为什么。任何想法都会非常感谢!

【问题讨论】:

    标签: python methods pygame init


    【解决方案1】:

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

    Group.update 的文档说这会调用每个精灵的update() 方法,因此如果您希望每个循环都调用该方法,则应将该方法重命名为update()

    【讨论】:

    • 我不认为它应该是神奇的任何东西,而是因为在通常会自动运行它的实例化方法中调用了 idleAnimation 方法。不过谢谢。
    【解决方案2】:

    __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(),因为它随后会在您的循环中运行。

    【讨论】:

      猜你喜欢
      • 2017-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多