Making Ammo In Gml

the code is made by: Generallucas from the Dutch Game Maker Community Original Tutorial

This tutorial describes how to create ammunition in Game maker, how to make clips, and how to reload.

First, put this in the create object of the player:

ammo=32
r_ammo=256
can_shoot=true

In this create event, we made 3 new variabeles:
-ammo, that checks how much ammo is in the clip you are using
-r_ammo, that checks how much spare ammo the player has.
-can_shoot, that checks if you are able to shoot. can_shoot is mostly used to prevent that the player can shoot a bullet in each step, but has to wait a few couple of steps before shooting another one.

The global left button event from the same object:

if can_shoot=true
{
  if ammo>0
  {
     ammo-=1
     alarm[0]=5 //When alarm 0 reaches 0, the player can shoot again.
     can_shoot=false
     instance_create(x,y,obj_bullet) //this creates a bullet. replace ''obj_bullet'' for the name of the bulletobject you are using.
  }
  else
  {
     if r_ammo>0 //in this code, the player reloads because he doesn't have ammo anymore in his clip. But he can only reload if he has spare ammo left.
     {
        alarm[1]=60  //this is de alarm event that indicates that the reloading has ended.
        can_shoot=false
        alarm[0]=-1
     }
  }
}

alarm 0 event:

can_shoot=true //the player can fire again.

put this in the alarm 1 event:

if r_ammo>(32-ammo) //In this code, the player has reloaded, and he now has a full clip of ammo... if he has enough spare ammo left.
{
   r_ammo-=(32-ammo)
   ammo=32
   can_shoot=true
}
else
{
  ammo+=r_ammo
  r_ammo=0
  can_shoot=true
}

Of course, the player must also be able to reload, even if the clip isn't empty yet. choose a event (like a button) in which the player is able to reload.
put the following code in this event:

if alarm[1]=-1 and r_ammo>0 and ammo<32 //alarm[1]=-1 checks if the player isn't already reloading.
{
  alarm[1]=60
  can_shoot=false
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License