I'm trying to make asteroids drop from the top straight to the bottom of the screen and then disappear. To do this I have made multiple objects of class Asteroid, however I can't delete them afterwards.
A = []
while gameLoop:
...
a = Asteroid()
A.append(a)`
for i in A:
i.move()
if i.pos > dWidth:
del i # This doesn't remove the object
Is there any way to delete them?
In pygame your objects should usually be subclasses of
pygame.sprite.Sprite
and should be stored in sprite groups which allow you to update and render all contained sprites by calling theupdate
anddraw
methods. You can remove the sprites from the corresponding groups by calling theirkill
method.In this example I add
Projectile
sprites to theall_sprites
group each frame andkill
them if they are outside of thegame_area
rect.pygame.Rect
s have acontains
method that you can use to check if one rect is inside of another rect. Alternatively, you can just check if the rect's x or y attributes are less than 0 or greater than the screen's width and height.You need to implement a
delete
method in theAsteroid
class, and calli.delete()
in yourif
condition.How to delete depends on how they are shown in the first place.