0
\$\begingroup\$

I'm having an issue with removing objects from a sprite Group. What is happening is I have a bullet class and every time the user presses the player shoots a bullet. I have 'alive = bool' code and all works great so long as only one instance of bullet is in the list. If multiple are in the list however only the last one gets removed. Does anyone know how I can fix this?

elif event.key == pygame.K_SPACE:
                # Fire a bullet if the user clicks the mouse button
                bullet = Bullet()
                bullet.bullet = bullet
                # Set the bullet so it is where the player is
                bullet.rect.x = player.rect.x + 9
                bullet.rect.y = player.rect.y
                # Add the bullet to the lists
                bullet_list.add(bullet)
                all_sprites_list.add(bullet)
                print(len(bullet_list))

    if bullet.alive == False:
        bullet_list.remove(bullet)
        all_sprites_list.remove(bullet)


#In the class
# If the bullet goes off the screen remove it
    if self.rect.y < 200:
        self.alive = False

I have it set to 200 at the moment for testing purposes.

Any help or a better way of doing this would be very much appreciated. Thank you in advance.

\$\endgroup\$
0
\$\begingroup\$

You need to use a loop and remove all bullets from the lists where alive == False. How your code is set up right now, bullet will be the last bullet created (it's only assigned to when a new bullet is created), and no other bullet will be tested or removed from the list.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.