在主循环中缩放精灵

问题描述

我想创建一个游戏,其中圆圈在表面上随机生成并开始增长。当两个圆圈相互接触时,游戏结束。因此,除了在循环期间调整精灵的大小外,一切正常。当我使用 transform.scale 时,我得到这样的结果:

Resizing using "transform.scale

然后我在文档中找到了 transform.smoothscale。我使用更改了我的代码来使用它,然后它看起来像这样:

Resizing using "transform.smoothscale"

我也尝试使用 Rect.inflate 但这对我的精灵没有任何影响。我尝试了 Rect.infalte_ip,如果我使用它,精灵不会增长,它更有可能移出框架。关于如何让这些 Sprite 原地生长以及它们应该如何调整大小的任何想法?

class Bubbles(pygame.sprite.Sprite):
def __init__(self):
    super().__init__()
    self.image_scale = 100
    self.image_scale_factor = 1
    self.image = resources.BUBBLE_SKIN[0].convert_alpha()
    self.image = pygame.transform.scale(self.image,(self.image_scale,self.image_scale))
    self.rect = self.image.get_rect()
    self.rect.centerx = (random.randrange(Settings.object_range_limit + (self.image_scale//2),(Settings.width - Settings.object_range_limit - self.image_scale)))
    self.rect.centery = (random.randrange(Settings.object_range_limit + (self.image_scale//2),(Settings.height - Settings.object_range_limit - self.image_scale)))

    self.growth_rate = random.randint(1,4)

def update(self):
    self.image_scale += self.growth_rate
    self.image = pygame.transform.scale(self.image,self.image_scale))

解决方法

您必须缩放原始精灵,而不是逐渐缩放精灵。每次扩展 sprint 时,质量都会下降。如果你逐渐缩放精灵,质量会越来越差。将精灵存储到属性 orignal_image 并缩放 orignal_image

如果要按图像中心缩放图像,则必须在使用新图像大小缩放图像后更新 rect 属性。
How do I scale a PyGame image (Surface) with respect to its center?

class Bubbles(pygame.sprite.Sprite):
    def __init__(self):
        # [...]
    
        self.image = resources.BUBBLE_SKIN[0].convert_alpha()
        self.image = pygame.transform.scale(
            self.image,(self.image_scale,self.image_scale))

        self.original_image =  self.image

    def update(self):
        self.image_scale += self.growth_rate
        self.image = pygame.transform.scale(
            self.original_image,self.image_scale))

        self.rect = self.image.get_rect(center = self.rect.center)