Game Maker Tutorial

Page 7 of 13
Enemies and Weaponry
But what is a scrolling shooter if you cannot shoot and there are no enemies? We will now extend our game with some enemy planes and a canon on the plane that you can fire.
Let us start with the canon. We need a bullet sprite. We put its origin in the centre as we did for the main plane. To make it a bit spectacular we use a rather large bullet. Exaggerating things is often important in games.
We create an object with this sprite. We will give it the default depth 0 such that it will appear below the plane but above the islands. The object has rather simple behavior. In the creation event we give it a vertical speed of –8 to make it move upwards. To avoid that more and more bullets keep flying around we must destroy it once it leaves the room.
This can easily be achieved. In the step event we test whether the variable x is smaller than –16. You should by now know how to do this. If so we destroy the object using the appropriate action. (You could also use the Outside room event that can be found in the other events.)
The bullet should be fired when the user presses the space key. As in most shooters the plane should keep on firing bullets as long as the key is pressed. But we don't want too many bullets at the same moment. This would make the game too easy.
We only allow the player to fire two bullets every second, that is, one bullet every 15 steps. To achieve this we use a variable can_shoot as we mentioned before. In the creation event of the main plane we set this variable to 1, indicating that we can indeed shoot a bullet. In the space key event we test whether the variable can_shoot is equal to 1. If so we create a bullet just in front of the ship, relative at position (0,-16). Also we set the variable can_shoot to 0 indicating that we can no longer shoot and set alarm0 to 15.
Remember that an alarm ticks down to 0 with one tick in each step. When the alarm reaches 0 the alarm event happens. In this event we set the variable can_shoot back to 1, indicating that we can shoot again. The event for the space key should now look something like this:
You can change the speed with which you can shoot by changing the value of the alarm clock. (In some games you can shoot faster if you are willing to constantly press the space key. This can be achieved by using a similar set of action in the space key pressed event but this time without the check for the variable.)
Let us now make the first enemy. It is a small plane that simply flies downwards. It does not shoot but when it hits the main plane the game is lost. Again we create a sprite for the enemy plane and an object. In the creation event we set the vertical speed to 4 to make the plane fly downwards. When the plane reaches the bottom of the room we make it reappear at a random place at the top of the room, in exactly the same way as we did for the islands. You should know how to do this by now.