Home > OS >  Pygame - Getting a bullet to fire up the screen on a MOUSEBUTTONDOWN event
Pygame - Getting a bullet to fire up the screen on a MOUSEBUTTONDOWN event

Time:10-22

Creating a space invaders style game using sprites as a pose to images - Trying to get the bullet to continually move up the screen until it detects that it's passed y = 0. I've got an function to fire that moves the bullet up, but only by 5 pixels per MOUSEBUTTONDOWN event detected. Ideally, it needs to continue moving to the top of the screen after only one event is fired.

Here is the relevant code concerning the bullet class and the event loop.

# bullet class

class Bullet(pygame.sprite.Sprite):
    def __init__(self,path):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(path)
        self.rect = self.image.get_rect()

    def shoot(self,pixels):
        self.rect.y -= pixels

    def track(self):
        bullet.rect.x = player.rect.x   23

And the event loop:

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()  
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player.moveLeft(5)
            if event.key == pygame.K_RIGHT:
                player.moveRight(5)
        if event.type == pygame.MOUSEBUTTONDOWN:
            bullet.shoot(5)
    
    bullet.track()
  
    playerGroup.update()
    gameDisplay.blit(backgroundImg,(0,0))
    playerGroup.draw(gameDisplay)

    bulletGroup.update()
    bulletGroup.draw(gameDisplay)

    pygame.display.update()
    clock.tick(60)

Thanks to anyone who answers my question.

CodePudding user response:

You can put an additional attribute shot in your bullet class. It is initially set to 0 and updated when the shoot method is called. Then the track method updates the y position of the bullet accordingly.

class Bullet(pygame.sprite.Sprite):
    def __init__(self,path):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(path)
        self.rect = self.image.get_rect()
        self.shot = 0  #  bullet not shot initially

    def shoot(self, pixels):
        self.shot = pixels

    def track(self):
        self.rect.y -= self.shot

So, as soon as the button is clicked, the shot attribute is modified and the bullet will keep moving.

  • Related