Pygame day 8: how to make a bullet sprite

1 https://youtu.be/wAKLVFMb7eE
2 https://youtu.be/rsBJgWqsoa4
3 https://youtu.be/J3k4-tqy_kM
4 https://youtu.be/vwYu9Eel9QM
5 https://youtu.be/UaPjKtuQyfA
6 https://youtu.be/ZuEc6gncGNs
7 https://youtu.be/wobJoDgI0LQ

This time we start with making a bullet sprite for the enemy, so that he can shoot at us. This is the first part, we will just place the bullet and make it visible, so that we understand what we’re doing. We also make the bullet point towards the player.

This is the new class for the bullet

class Bullet():
	def __init__(self):
		self.x = enemy.x
		self.y = enemy.y
		self.image = pygame.image.load("img/bullet.png").convert()
		self.rect = self.image.get_rect()

	def draw(self):
		if enemy.x < player.x:
			self.rect[0] = enemy.x + 50
		if enemy.x > player.x:
			self.rect[0] = enemy.x
		if abs(enemy.x - player.x) < 8:
			self.rect[0] = enemy.x + 24


		if enemy.y > player.y:
			self.rect[1] = enemy.y
		if enemy.y < player.y:
			self.rect[1] = enemy.y + 50
		if abs(enemy.y - player.y) < 8:
			self.rect[1] = enemy.y + 24
		screen.blit(self.image, self.rect)

This is the instance fo the 3 sprites now

player = Player(0,0)
enemy = Enemy(100,100)
bullet = Bullet()

in the mainloop nethod of the Screen class we show the bullet like this, with bullet.draw

		Screen.check_collision()
		screen.fill(0)
		show_fps()
		player.draw()
		enemy.draw()
		bullet.draw()
		enemy.move_ai()
		pygame.display.update()
		clock.tick(60)

So to create a bullet we:

  • created a class Bullet
  • made an istance of Bullet called bullet
  • call every frame the method bullet.draw to show it
    • in this method we compare the position of player and enemy to position the bullet
https://github.com/formazione/pygame_days

https://github.com/formazione/pygame_days


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.