Tutorial 8: Creating Enemy Lazer / Bullet
Go to the Assets Browser resources area menu:
- Right click on Sprites and click Create Sprite or you can click on Resources menu at the top of GameMaker studio.
- Make sure you name your sprites correctly – always prefix your sprites with the letter spr
- Name the sprite sprEnemyLazer
- Click the Import button
- Browse to where you have saved the enemy lazer or bullet graphic
- Set the Origin Point to Top Centre
Why? You want the enemy lazer to start at the top point, if the enemy is shooting down towards you.
Create the enemy lazer / bullet object
Under Resources:
- Right click Object and click Create object
- Name the object objEnemyLazer
- Assign sprEnemyLazer sprite you just created by clicking the 3 dots in the box beside No Sprite
Make the enemy lazer move
- Click Add Event button in the Events box and add a Create event
- In the description comment change the description to Enemy Lazer Variables.
- And add the code:
flySpeed = 15; //speed of enemy lazer
Destroy the enemy lazer object when it leaves the room
The enemy lazer object still exists as it leaves the room. Therefore, it is good practice to destroy that object when it leaves the room to free up computer memory.
- Add the following event to objEnemyLazer – Other – Outside Room
Add this code to the Outside Room event:
instance_destroy();
Make the enemy lazer / bullet move down the screen
- Add a Step Event to your lazer or bullet object
- Add the following code to the step event:
y += flySpeed;
//moves objEnemyLazer down the room.
//This would change to x if the enemy was shooting across the room towards the player object
Add an alarm event to the Enemy object
What is an alarm? An alarm event is an event that must be triggered. You tell an alarm to go off initially in a Create or Step event. We tell the Enemy Object to shoot the lazer.
- Open the enemy object objEnemy1
- Add an Alarm Event to it – Alarm 0
- Add the following code to the alarm event
instance_create_layer(x,y,layer,objEnemyLazer);
Note: You could also add a sound here for the enemy lazer. Go back to how to the adding sounds tutorial, but put the code to create the sound into the enemy Alarm event
How often do you want your enemy to fire?
- In the Create Event for enemy objEnemy1 , add the following code to randomise the setup times for the alarm events:
fireRateLow = 20; //2 frames
fireRateHigh = 60; //6 frames
alarm[0] = 120; //first time the alarm is triggered will be 120 frames into the game
- In the Alarm Event of objEnemy1, reset the alarm to tell the alarm when to trigger again.
Add this code to the enemy alarm event:
alarm[0] = irandom_range(fireRateLow, fireRateHigh);