QuantumAtom
QuantumAtom

Reputation: 43

Is there a way to kill a Pygame sprite without having to kill it in a group?

I have a single ball sprite and I don't really have a need for a group. I want to set that sprite to be deleted (or killed) when it reaches the end of the screen, also so it generates another one. I am trying to do this without a group and wanted to know if this is possible. Thank you for your expertise.

I tried self.kill() and kill.self in an update method for the sprite class. That didn't work. I tried to do a kill in the screen update loop for the application. That didn't work. I have done extensive research and all the answer are only when using groups. I also tried to do "if not pygame.surface.rect.contains(Ball())" and that didn't work. (It is something like that, I tried several variations of that expression.)

def update(self):
    """Move the ball down"""
    self.y = self.y + 1
    self.rect.y = self.y 
    #print("Screen is: " + str(pygame.surface.rect()))
    print("Object is: " + str(self.rect))
    if (self.rect.y >= 800):
         self.kill()





def update_screen(screen, ball, lamp):
    #Show on the screen
    screen.fill((135,206,250))
    lamp.blitme()
    ball.blitme()
    ballgen(screen)
    ball.update()
    lamp.update()
    pygame.display.flip()

I expected the results to stop counting the rect of the ball, but it keeps counting up, thus making me think that it is not being removed.

Upvotes: 0

Views: 1362

Answers (1)

sloth
sloth

Reputation: 101122

If you don't use the Group class, there's no point in calling the Sprite.kill method. All it does is to remove the Sprite from all of its groups. Calling kill does not magically remove the Sprite from your game.

If you want to have a Sprite removed, just stop using it: either stop calling ball.blitme() and ball.update() in your update_screen function, or replace ball with a new instance of your Sprite's class.

But consider starting to actually use the Group class. It'll make your life easier.

To check if the ball is inside the screen, instead of

if not pygame.surface.rect.contains(Ball())

use

if not pygame.display.get_surface().get_rect().contains(self.rect):
    self.rect.center = (whatever_new_position, ....)

in Ball's update method. pygame.display.get_surface() will get you the screen surface, get_rect() will get you the Rect of that Surface, and contains() will check if the Rect of the Ball is still inside the screen.

Then we just set a new position for the ball.

Also note that there's usually no need for an x and y attribute in a sprite class since the position is already stored in the rect attribute.

Upvotes: 1

Related Questions