Python Forum

Full Version: pygame, help with making a function to detect collision between player and enemy.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys.

I am making a game in pygame, where you play as a little spaceship and your mission is to shoot aliens. I am struggling on making a function, when the spaceship hits one of the enemies, i want the game to be game over. I have made a collision function for the missile, when it hits the enemy, the enemy respawn and you get + 1 in score and it works fine, but i am struggling with this.

Hope you can understand my code, but ask if there is any questions. I have used a long time on the game so i hope someone can help me!
Best regards.

Kris.

Here is my code:

https://pastebin.com/5V3d1hTc
Why aren't you using the pygame sprite class? Pygame has collision detection built in. It would be simple, like this for example.

hit = pygame.sprite.spritecollide(player, enemies, True)

if hit:
   game_over()
So, the answer is to use the Sprite class and sprite groups.
I would also suggest a restructuring for a player class and an enemy class to help make things more organized. My tutorial series 1-9 actually uses a space shooter type game with similar properties. Regarding your issue, specifically this one.
Hey again. Sorry for the long answer. I have been a little busy the last couple of weeks.
Thanks for the answer, i would try and read about classes in my Python book and look into it after.
:D