I am unable to use get_rect with Convert/convert_alpha and subsurface

Asked

Viewed 93 times

0

I was doing so:

class Esqueleto (pygame.sprite.Sprite):
    def __init__ (self):
        self.imagem = pygame.image.load("imagem/esqueleto.png")
        self.rect = self.imagem.get_rect()
        self.imagem = self.imagem.convert_alpha()
    def desenhar (self, superficie):
        superficie.blit(self.imagem.subsurface([self.coluna * self.tile_size, self.linha * self.tile_size, self.tile_size, self.tile_size]), self.rect)

The problem is that this way the width and height of the rect will be those of the spritesheet not of the cutout. I can’t think of a way to use get_rect to pick up the dimensions of the cutout.

1 answer

0

If your problem is just height and width, simply create a rectangle with x and y = 0 and width and height = self. _tile_size - no need to create a rectangle based on the disk image read:

self.rect = pygame.Rect((0, 0, self.tile_size, self.tile_size))

(You however do not configure self.tile_size within the __init__. Where does the tile_size? if it is a global varipavel, the prefix self. is not necessary)

But, going beyond that, with this code you’re not harnessing the full potential of the pygame "Sprite" subclasses: If your self.rect you have the desired position on the screen for your Sprite, and the attribute self.image already contain the desired subsurface, the pygame can draw its Sprite automatically when you call the method draw of a group containing your image.

tile_size = 128  # exemplo

class Esqueleto (pygame.sprite.Sprite):
    def __init__ (self):
        self.sprite_sheet = pygame.image.load("imagem/esqueleto.png")
        self.rect = self.imagem.get_rect()
        self.imagem = self.imagem.convert_alpha()
    def update (self):
        self.image = self.sprite_sheet.subsurface([self.coluna * tile_size, self.linha * tile_size, tile_size, tile_size]))
        self.rect.x = ... # posicao x em que o objeto será desenhado na tela
        self.rect.y = ... # posicao y em que o objeto será desenhado na tela
    # def draw(self, superficie): 
          # não é necessário esse método:
          #  - o método "draw" do Group ja faz blit de
          # self.image na posição delimitada por self.rect

And to use that, put your sprites in a group (pygame.sprite.Group or derivative), and call the methods update and draw of the group. (The first calls the update of each Prite in the group, the second makes the blit).

https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group

Browser other questions tagged

You are not signed in. Login or sign up in order to post.