1

my code is copied below

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()

traceback:

 File "C:\Users\bobby\AppData\Local\Programs\Python\Python311\Lib\site-packages\pygame\sprite.py", line 551, in draw
   zip(sprites, surface.blits((spr.image, spr.rect) for spr in sprites))        
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 File "C:\Users\bobby\AppData\Local\Programs\Python\Python311\Lib\site-packages\pygame\sprite.py", line 551, in <genexpr>
   zip(sprites, surface.blits((spr.image, spr.rect) for spr in sprites))        
                                          ^^^^^^^^
AttributeError: 'Bullet' object has no attribute 'rect'

attempting to spawn in a bullet however the get_rect function from pygame to produce its hitbox is not working

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
bobby_52
  • 11
  • 1

1 Answers1

1

A pygame.sprite.Sprite object must have the attributes image and rect. So rename hitbox to 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()

Also see How can I add objects to a "pygame.sprite.Group()"? and What does pygame.sprite.Group() do or read the documentation of pygame.sprite.Group.draw:

Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect for the position.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174