Scale a sprite size

Viewed 274

I have sprites running around a simulator.

class guys(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("/Users/taiji/Desktop/Sim/images/guys.png")
        self.original_image = self.image
        self.surf = pygame.Surface((50, 30))
        pos = (random.uniform(0,SCREEN_WIDTH), random.uniform(0,300))
        self.rect = self.surf.get_rect(center = pos)

I would like to shrink them in size from (50, 30) to (5, 3). Later on I'll have them grow based on energy so I'll change that (5, 3) to something else, but I'm just trying to get the basics down now. I tried this:

def grow(sprites):
    for entity in sprites:
        pygame.transform.scale(entity.surf, (5, 3))

But they didn't change at all. Can someone help me with this? Do I need to do anything to entity.rect so that collisions are still ok?

Thank you for the help!

1 Answers

This occurs because pygame.transform.scale() does not operate in place. This can be solved by assigning the surface to the function output, like so:

entity.surf = pygame.transform.scale(entity.surf, (5, 3))

As a note, this method is considered destructive, and thus scaling back up would likely lead to the sprites being unrecognizable. One way to solve this is to save the initial sprite (as it seems you've already done with self.original_image) and simply set the new sprite to a scaled version of that original.

Related