Search code examples
pythonlistpygameprojectile

Shooting multiple projectiles in pygame


I have a Missile class that gets the Player's position when the spacebar is pressed. .fire() uses this position to shoot a missile. It only shoots one at a time, how would I shoot multiple? I heard using a list would help.

class Missile(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        # Get image of the whole spritesheet
        self.imgMaster = pygame.image.load("Royalty-Free-Game-art-Spaceships-from-Unlucky-Studio.png")
        self.imgMaster.convert()
        misImgSize = (45, 77)
        # Create a surface to draw a section of the spritesheet
        self.image = pygame.Surface(misImgSize)
        self.image.blit(self.imgMaster, (0,0), ( (71, 1956) ,(misImgSize)) )
        self.image.set_colorkey( self.image.get_at((1,1)))
        self.image = pygame.transform.scale( self.image, (15, 35) )
        # Get rect of sprite
        self.rect = self.image.get_rect()
        # Place missile off-screen at first
        self.rect.center = (-100, -100)
        self.dy = 0

    def fire(self, player_pos):
            self.rect.center = player_pos  # Move Bomb to cannon.
            self.dy = BOMB_SpeedY              # Set its velocity.

    
    def update(self):
        self.rect.centery -= self.dy
    
    def reset(self):
        self.rect.center = (-100, -100)     # This location is off-screen!
        self.dx = 0

Code in the event handler:

clock = pygame.time.Clock()
#  - Set a loop that keeps running until user quits or proceeds
keepGoing = True
while keepGoing:
    # Set FPS of the game - 30 frames per second/tick
    clock.tick(CLOCK_TICK)
    # Every 30 ticks is a second
    tickCount += 1

# Handle any events
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        keepGoing = False 
        print("hi!")
    if event.type == pygame.KEYDOWN:

        if event.key == pygame.K_SPACE:
            missile.fire(player.get_pos())

Solution

  • You have to create a Group for the missiles. When SPACE is pressed create a new instance of Missile and add it to the list:

    missilesGroup = pygame.sprite.Group()
    
    keepGoing = True
    while keepGoing:
        # [...]
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                keepGoing = False 
                print("hi!")
    
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    missile = Missile()
                    missile.fire(player.get_pos())
                    missilesGroup.add(missile)
    

    I recommend to add the new missile also to the Group of all Sprites.

    Do not "reset" a missile, but use kill to remove it:

    class Missile(pygame.sprite.Sprite):
        # [...]
    
        def reset(self):
            self.kill()
    

    See kill

    remove the Sprite from all Groups