繁体   English   中英

精灵组中的精灵方法Pygame

[英]Sprite Methods in Sprite Groups Pygame

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

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

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

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

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

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

你的组的update()方法只会调用你的sprite的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() ,因为它将在您的循环中运行。

暂无
暂无

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

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