Python and Turtle python Asteroids Tutorial- Bullets

Asteroids Tutorial- Bullets

The Bullets Class

First, we need to create bullet class. There should be some variables that apply to all the bullets, such as its speed and how range. The starting location of each bullet should be different, so the initial x and y location should be instance variables.

A close up of a logo

Description automatically generated

Drawing the Bullet

This part can be varied by the programmer. Here, we made the bullet simply a dot. It should appear at the point of the spaceship, so move the bullet there. Be sure to only draw the bullet if the bullet still has range left.

A close up of a logo

Description automatically generated

Moving the Bullet

As the bullet moves, its range should fall (you don’t want the bullet moving forever). The amount you want to move is, as usual, speed multiplied by time. However, you must move the bullet in both the x direction and the y direction. The distance is speed * time, but you need to calculate the x and y component. See the code for the answer.

Execution

Animation

If you want to show the bullet moving, pass in short time interval to the move method (the smaller it is, the smoother the animation). After moving the bullet, clear the screen and draw the bullet again. If the bullet hits its maximum range,  stop the animation.

A close up of a sign

Description automatically generated

Firing

The list bullets contains all the bullets in the queue or currently animated. If the last bullet still has life left, you should not fire (to limit the amount of bullets). Otherwise, add a bullet to the list. At the moment, put it in a random location and add it to the list; when we combine the different files, we will make the bullet go to the  spaceship. Note that currently, everything under the execution header happens only if the code is run independently. After we combine the files, fire and animation will be slightly different.

View this link for the full code: https://github.com/HaimingXu679/Asteroids/blob/master/bullet.py

Related Post