【问题标题】:how do i fix this pygame error AttributeError: 'Bullet' object has no attribute 'rect'我该如何修复这个 pygame 错误 AttributeError: \'Bullet\' object has no attribute \'rect\'
【发布时间】:2023-01-13 05:11:11
【问题描述】:

我的代码复制在下面

class Bullet(pygame.sprite.Sprite):
    def __init__(self ,x, y, direction):
        pygame.sprite.Sprite.__init__(self)
        self.speed = 10
        self.image = bullet_img
        self.hitbox = self.image.get_rect()
        self.hitbox.center = (x,y)
        self.direction = direction


    def update(self):
        #move bullet
        self.hitbox.x +=(self.direction*self.speed)
        #check if bullet off screen
        if self.hitbox.right <0 or self.hitbox.left>SCREEN_WIDTH:
            self.kill()

追溯:

文件“C:\Users\bobby\AppData\Local\Programs\Python\Python311\Lib\site-packages\pygame\sprite.py”,第 551 行,在绘图中 zip(sprites, surface.blits((spr.image, spr.rect) for sprite in sprites))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^ 文件“C:\Users\bobby\AppData\Local\Programs\Python\Python311\Lib\site-packages\pygame\sprite.py”,第 551 行,在 zip(sprites, surface.blits((spr.image, spr.rect) for sprite in sprites))
^^^^^^^^ AttributeError: 'Bullet' 对象没有属性 'rect'

谢谢你

试图在子弹中生成,但是 pygame 中用于生成其命中框的 get_rect 函数无法正常工作

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    pygame.sprite.Sprite 对象必须具有属性 imagerect。所以将hitbox重命名为rect

    class Bullet(pygame.sprite.Sprite):
        def __init__(self ,x, y, direction):
            pygame.sprite.Sprite.__init__(self)
            self.speed = 10
            self.image = bullet_img
            self.rect = self.image.get_rect()
            self.rect.center = (x,y)
            self.direction = direction
    
        def update(self):
            #move bullet
            self.rect.x +=(self.direction*self.speed)
            #check if bullet off screen
            if self.rect.right <0 or self.rect.left>SCREEN_WIDTH:
                self.kill()
    

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 2018-02-05
      • 2019-07-19
      • 2023-01-23
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 2022-12-03
      相关资源
      最近更新 更多