【问题标题】:How can I put the rect of a sprite in the center of the image如何将精灵的矩形放在图像的中心
【发布时间】:2023-02-23 02:41:07
【问题描述】:

enter image description here

这是我到目前为止所拥有的,我已经绘制了矩形来跟踪它,这是代码:

class Personagem(pygame.sprite.Sprite):
      def __init__(self,x,y):
            super().__init__()
            self.imagem = pygame.image.load('sprites/frente-parado.bmp')
            self.rect = self.imagem.get_rect()
            self.rect.height = 20
            self.rect.width = 20
            self.rect.centerx = x
            self.rect.centery = y
            self.velocidade_x = 0
            self.velocidade_y = 0

我一直在这里查看类似的问题,我曾尝试创建另一个从原始左下角开始的矩形,但后来我无法碰撞它,因为精灵最终有两个矩形

我感谢任何答案,抱歉英语不好

【问题讨论】:

    标签: python pygame sprite rect collider


    【解决方案1】:

    要使图像中精灵的矩形居中,可以使用矩形的 center 属性代替 centerx 和 centery。这是以 rect 为中心的代码的更新版本:

    class Personagem(pygame.sprite.Sprite):
        def __init__(self, x, y):
            super().__init__()
            self.imagem = pygame.image.load('sprites/frente-parado.bmp')
            self.rect = self.imagem.get_rect()
            self.rect.width = 20
            self.rect.height = 20
            self.rect.center = (x, y)
            self.velocidade_x = 0
            self.velocidade_y = 0
    

    在此版本中,矩形的中心属性设置为元组 (x, y),这将使矩形在图像中居中。请注意,我还调换了宽度和高度属性的顺序,因为建议在使用 pygame 时将宽度设置在高度之前。

    【讨论】:

    • self.rect.center = (x, y)self.rect.centerx = x self.rect.centery = y 完全一样。所以你的答案中提出的解决方案不会改变任何东西。
    • 我尝试这样做,但矩形保持在图像的左上角,与我在问题中链接的图像非常相似,但这次它更接近角色的头部,我认为问题可能出在 blit per = Personagem(40,40) tela.blit(per.imagem,per)
    【解决方案2】:

    好吧,我找到了一种方法,它有点难看,但它有效

    x = per.rect.topleft[0] - 10 y = per.rect.topleft[1] - 10 tela.blit(per.imagem,(x,y))

    enter image description here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      • 2012-08-27
      • 2020-03-13
      • 1970-01-01
      相关资源
      最近更新 更多