pygame如何实现sprite的rect

时间:2019-02-20 21:55:31

标签: python pygame sprite

我正在学习pygame,遇到一个问题: 当我尝试通过更改变量self.image然后self.rect的内容来更改Sprite的图像时,它不会显示/剪切此新图像。这是代码,希望能让自己理解。

all_sprites_list = pygame.sprite.Group()
luffy_sprites_ls = pygame.sprite.Group()

class luffy(pygame.sprite.Sprite):
    """docstring pour le personnage"""
    def __init__(self):
        self.lsLuffy = []
        self.lsLuffySauter = []
        super().__init__()
        self.imageAll = SpriteSheet("images/attaquesLuffy.png")
        #loading some img to put them in a lsLuffySauter
        self.image = self.imageAll.get_image(35, 74, 20, 95)
        self.lsLuffySauter.append(self.image)
        self.image2 = self.imageAll.get_image(200, 300, 300,300)
        self.lsLuffySauter.append(self.image2)

        self.rect = self.image.get_rect()
        self.rect.x = 500
        self.rect.y = 500
        all_sprites_list.add(self)
        self.positionX = 500
        self.positionY = 500

    def sauter(self):
        """ Called when user hits 'jump' button. """
        self.current_image = self.lsLuffySauter[0]
        self.positionY -= 10
        self.rect = self.current_image.get_rect()
        self.rect.x = self.positionX
        self.rect.y = self.positionY
        luffy_sprites_ls.empty()
        luffy_sprites_ls.add(self)
        #all_sprites_list.update()

#Code to draw in the screen
    screen.fill(WHITE)
    all_sprites_list.draw((screen))
    luffy_sprites_ls.draw((screen))
    pygame.display.flip()
    clock.tick(100)

1 个答案:

答案 0 :(得分:1)

在调用pygame.sprite.Group.draw()时(如luffy_sprites_ls.draw((screen))一样,组中的每个子画面都将sprite.image渲染到sprite.rect的屏幕上。

您的sauter()函数正在更改luffy.rect,但不是正在更改luffy.image(正在更改luffy.current_image)。

可能您想要类似的东西:

def sauter(self):
    """ Called when user hits 'jump' button. """
    self.image = self.lsLuffySauter[0]
    self.positionY -= 10
    self.rect = self.image.get_rect()
    self.rect.x = self.positionX
    self.rect.y = self.positionY