For part I of this tutorial, refer
Tutorial for making Platforming game with GameMaker Lite Part I
In this tutorial Ill be teaching you how to add a shootable gun to your platforming game. Well be starting off from Part I of this tutorial.
The gun will be placed somewhere in the level. Once you pick it up, you can shoot with it using the space key.
Start by creating a sprite for your gun. Name it “Gun”.
Create an object with the same sprite. Name it “Gun” as well.
In the Gun object, define a global variable which indicates if we can shoot or not.
To do this
Make an event which triggers on creation and have it execute this code:
global.Can_Shoot = 0;
Then create an even which triggers on collision with our Player object. Insert this code in it:
global.Can_Shoot = 1;
instance_destroy();
This lets us know that we can now shoot. It also destroys the Gun object.
Now open up our player object.
Insert this code along with the code to be executed on create:
fire_rate = 0;
Insert this in the step code:
fire_rate -= 1;
Once we fire our gun once, the fire rate will get resetted back to 50. We will be able to fire only once it reaches 0 again ie. in 50 steps. Ive used this method instead of GM’s inbuilt timer.
Create two gun sprites. One for facing left and the other facing right.
Create objects for them as well. Name one Bullet)Left and the other Bullet_Right.
Insert this code in the Bullet facing Left:
Create:
direction= 180;
speed= 5;
On collision with Block:
instance_destroy();
Insert this code in the Bullet facing Right:
Create:
direction= 0;
speed= 5;
On collision with Block:
instance_destroy();
In the Player object, create an event which triggers on pressing the space bar and insert this code:
if (global.Can_Shoot == 1)
{
if(fire_rate<=0) { if(dir==0) { instance_create(x,y,Bullet_Left); fire_rate=50; } if(dir==1) { instance_create(x,y,Bullet_Right); fire_rate=50; } } }
Right. Now just place your Gun object somewhere in the map and test it out.
The Gun should disappear when you touch it. You should be able to fire bullets at a fixed interval in whatever direction you are facing using the space key.
Good Luck. Comment here if you have any issues or if you need any of the code to be explained 🙂