In this project, we add missile firing using our button.

The hardware setup for this project should be the same setup that was completed for the project. Here's a reminder:

In this project, we're going to add the ability to fire missiles.

The first step is to initialize the button that we'll use to fire the missiles in our initialization section. We do this by importing the function that we will use, creating a Button object associated with our firing button and then initializing the position of our missile (we'll only allow one missile to be on the screen at a given time so we only need one set of rectangular coordinates for the missile). Our left/right coordinate will be X and our up/down coordinate will be Y, which is pretty standard.

We also will want to create two other variables — one that will define the color of the missile (we can make it less bright than the other objects on the LED Matrix screen to give it a unique look) and one that will define how quickly the missile will move (in terms of number of seconds between drawing updates).

Here is what this piece of code will look like:

Next, we need to make changes to our game loop to support the missiles. This involves three parts of the loop:

Getting inputs

In terms of getting inputs, we'll first want to check the button to determine when it's pressed. And we'll then want to get the current time to determine if enough time has elapsed that we need to move any existing missiles on the screen:

Changing the world:

To change the world, we'll first need to check if either:

  1. A missile was already launched and it's time to move it: We'll know this if missile_x >= 0, and MISSILE_STEP_TIME time has passed since the missile last moved. If so, we'll move the missile up, but if it goes past the top of the LED Matrix display, we'll remove it.

  2. The fire button was pressed: If so, we'll create a new missile, just above the ship.

Show the world:

To show the world, we'll check to see if there is an existing missile on the screen, and if there is, we'll draw its current location.

If we integrate those snippets of code into our current code for the project, our full project will look like this — when you run it, try pressing the button and watching the missile fire:

  1. Change the missile speed to as fast as possible, but so you can still see it.

  2. Change the missile color to as light as possible, without being invisible.

  3. Can you make missile quickly flash on and off as it moves up the screen?

  4. Our missile restarts shooting from the spaceship every time the button is pressed. Can you ignore button presses while the missile is shooting so that a missile always makes it to the top of the display?

  5. Can you add a second missile, so that you can shoot up to two missiles at a time?