如何从顶部降低矩形的高度?

How to decrease the height of a rectangle, from the top?

我正在我的游戏中实现一个我的角色躲避的功能。因此我想降低播放器矩形的高度。

我已经尝试用 rect.inflate(0,y)rect.h = new_height 来做到这一点。 然而,我 运行 遇到的问题是这些方法降低了底部的矩形高度。如何降低顶部的高度?

class Player(pygame.sprite.Sprite):
    def __init__(self, pos, groups):
        super().__init__(groups)
        self.ducking = False

        self.image = pygame.image.load('Player/Player0.png').convert_alpha()
        self.rect = self.image.get_rect(topleft = pos)
    
    def duck(self):
        if self.ducking: # This bool becomes True in another method
            self.image = pygame.image.load('Player/Player_duck.png')).convert_alpha()
            
            # Decrease rect height
            self.rect.h = new_height

您必须更改矩形顶部以及高度 - 并使用高度差计算顶部必须移动多少。

编程时,你想做的每件事都不会有调用或属性,思考和创建策略以获得你需要的结果是其中的一部分交易:

# on game toplevel, or inside a proper setup/init function:
ducked_image = pygame.image.load('Player/Player_duck.png')).convert_alpha()

...

class Player(...):

    ...

    def duck(self):
        if self.ducking: # This bool becomes True in another method
            self.image = ducked_image
            
            new_height = ducked_image.get_rect().h
            self.rect.top += self.rect.h - new_height
            self.rect.h = new_height