Day 2: Tower Defense in Python: Shooting

Objective: To spawn bullet objects and shoot them in the direction of the mouse pointer.

Now that we have a game window and we are initializing the castle in the correct position, we can now work on the shooting aspect of this tower defense game.

We need to define a bullet class underneath the castle class of our main python script.

The bullet itself will inherit from the sprite class in pygame. This is evident in that we are passing a pygame sprite object into the bullet instance. In order to use the methods that perform more advanced math well need to type import math at the top of this script.

Now inside of our Castle class that we created in the last segment, we are going to create a function that spawns a bullet at a specified location and makes it travel in the direction of the mouse pointer.

We add the shoot function into the Castle class of our main script

At the top before the game loop begins we need to assigns a sprite to represent the bullet instance. Also, because we are working with the sprite class we HAVE to create a sprite group.

Now we simply call the shoot function in our game loop while it is running. This can be seen being implemented in the image below.

The effect can be seen in the gif at the top of the article.

Unity Dev . Web Dev . RN