I am not able to use get_rect with convert / convert_alpha and subsurface

0

I was doing this:

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 in this way the width and height of the rect will be those of the spritesheet not that of the cutout. I can not think of a way to use get_rect to get the dimensions of the clipping.

    
asked by anonymous 24.10.2017 / 16:28

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 - you do not need to create a rectangle based on the read disk image:

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

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

But going further, with this code you're not taking full advantage of the pygame sprite subclasses: If your self.rect has the desired position on the screen for your sprite, and the self.image attribute already contains the desired subsurface, pygame can draw your sprite automatically when you call the draw method 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 this, put your sprites in a group ( pygame.sprite.Group or derived), and call the methods update and draw of the group. (The first one calls the update of each sprite in the group, the second one does the blit).

link

    
26.10.2017 / 03:22