Lasers, broken down.

gameshot
The first game that I made using pygame was a remake of the classic Asteroids game. One of the biggest challenges I faced was properly colliding objects together. I tried to google everything that I could, and all of the documentation I came across had examples using sprites. I used Pygame.org, and some other various resources to help me use sprites in my code. 

gamedisplay

The lasers were one of the trickiest objects to collide. To start I had to create a Weapon Class as a pygame.sprite object.  Each sprite object has a rectangle, so I turned the laser image into a rectangle. I assigned the x and y coordinates to the rectangle center and bottom, and assigned a speed. 

weapons_class

Next, I added an attack module inside of the Player_1 class, and created a variable calling the x and y coordinates of the rectangle/laser image in the Weapons class.  I added that variable to the all sprites group and to the lasers group.

player_class

Inside of the while loop I created a variable for the all_sprites group. I also assigned the enemy and lasers to their own sprite groups. I used a for loop to generate the enemy sprite, and add it to the all_sprites and enemy group.  

while

To shoot the laser I created an event.type for holding down the space key and called the attack function inside of the player object. 

event

To detect collision between the laser and the enemy sprite group. I used pygame.sprite.groupcollide(group1, group2, True(group1), True(group2). When True, the sprite groups disappear from the screen. To keep the game running I assigned groupcollide to a variable, and inserted a for statement to repopulate the enemy objects that were hit.

collide

One great thing about using sprites is that it saves you from having to update all of your objects individually. I assigned all the sprite objects to a sprite group named all_sprites and updated them all at once. I also rendered them to the screen at the end of my code using all_sprites.draw(screen).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s