๐Ÿš€ Coding the Projectiles | myBetabox

๐Ÿš€ Coding the Projectiles

Keyboard Guide

Coding the Projectiles

The Code Explained

Your arcade hero needs to attack enemies with something! We’re going to set up a projectile class andย object.

๐ŸŒŸย Classesย create objects with the same properties and are written asย class ClassName:ย with our in-game example beingย class Projectile(pygame.sprite.Sprite):

Aย tuple is an ordered data set as shown by (20, 30). Make sure to capitalize .Surface() and know that .Surface() always uses a tuple.

self.image = pygame.Surface((20, 30))

๐ŸŒŸ Tuples, like lists, are ordered and have indexes but, unlike lists, the order cannot change.

Code the projectile image and its properties by giving it a ‘placemat’ to sit on.

self.image = projectile_img
self.image = pygame.transform.scale(prjectile_img, (20, 30))
self.rect = self.image.get_rect()

Now position that ‘placemat’ rectangle. The y position is the up/down vertical and the x position is the left/right horizontal.

self.rect.bottom = y
self.rect.centerx = x

When we code the speed of the projectiles, we have to keep direction in mind. In Python, when a sprite moves from the top of the screen to the bottom, it is a positive value. Since our hero aims the projectiles upward (from bottom to top) we must use a negative value.

self.speedy = -10

Our game should update whenever our projectiles move positions during gameplay so they look like they’re moving in real time.

self.rect.y += self.speedy

We should also let the game know when a projectile misses an enemy and continues offscreen by using an if conditional statement. To get rid of objects in Python we use a function called kill(). This will delete the projectiles that veer offscreen.

if self.rect.bottom < 0:
ย  ย self.kill()

๐ŸŒŸย Conditionals are โ€˜ifโ€™ statements that compare two values to see if it’s true. If statements always have a : at the end.

๐ŸŒŸ Functionsย are packets of code that do a certain task and are always followed by ( ). The function we use here is self.kill() used to remove projectiles from the screen.