1

I am trying to create a space invaders like game and have created the player and the firing mechanic. However, I am struggling with the asteroids as the collisions seem to be behaving incorrectly.

As shown here: https://gyazo.com/495dda6909b8436c98fea0d8ca55c6d0

My collision code:

def update(self, asteroids):
        if self.rect.y > 0:
            self.rect.y -= self.speed
        else:
            self.kill()
            
        for asteroid in asteroids:
            if self.rect.colliderect(asteroid.rect):
                self.kill()

Adding a print message shows that the second kill command is being executed. I have no idea why this is occuring. Any help is appreciated. Thank you.

Edit: Yes, there is an asteroid and bullet sprite group. If you need the code, it is on my github. Here: https://github.com/RespectedCow/space-invaders

Edit: Fixed it. After printing the rect of the asteroid I figured out that the asteroid's size was configured after I did get_rect() on the surface, resulting in the rect being much larger than it should be thereby causing the issue. I simply moved the code that changes the surface's size on top of the code that got the rect from it.

Cowman
  • 11
  • 4
  • Is the player in a [`pygame.sprite.Group`](https://www.pygame.org/docs/ref/sprite.html)? [`kill`](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite.kill) just removes the sprite from all _Groups_ – Rabbid76 Jul 22 '22 at 12:56
  • The player is in not in any sprite group. That code is in the "Bullet" class. – Cowman Jul 23 '22 at 12:19
  • That's why it does not work. `kill` just removes the _Sprite_ from the _Groups_. `kill` doesn't have any effect if the _Sprite_ is not in a _Group_. – Rabbid76 Jul 23 '22 at 12:22
  • The player sprite is not killed as I have not implemented a hp system. Only the asteroid and bullets are killed and they're in their own respective groups. Sorry for my unclear post. – Cowman Jul 24 '22 at 14:29
  • We can't tell from the code in the question if the player is in a _Group_. `kill` does nothing with a _Sprite_ that is not in a _Group_. You need to put the code in the question. Links to external resources tend to break or the content may change. – Rabbid76 Jul 24 '22 at 14:48
  • self.kill() only occurs in the bullet. The issue is that colliderect is returning true when it isn't meant to as shown in the external resources. The code is across multiple files so I'm unsure as to how to create an MRE. – Cowman Jul 26 '22 at 15:45

1 Answers1

0

Hmm, as Rabbid76 pointed out in a comment, .kill is used for sprite groups. But I can't really help without more code here, as I have no idea how your game functions. I personally would just recommend having some splash screen that pauses the game and says "You got hit" and resets the game state. But if you give me more info I can try and help you to the best of my ability.

Dominic B.
  • 77
  • 7