Upgrade Ammo Display- Game Dev Series 142
Objective: upgrade the ammo display interface from total ammo counts to magazine included ammo counts.
In this tutorial, I would show the idea of display the ammo amount with both magazine and total amount, instead of showing total ammo amount only.
This would not be a complicated method, just display the amount with some basic calculation and logic.
Here are some concepts that would be done in this tutorial:
- Shooting would only decrease the ammo amount from magazine.
- The total amount would become ammo left, which would only decrease when reloading and increase when picking up some ammo.
- It is not available to fire when magazine is empty.
- It is not available to reload when no ammo left.
These 4 function would be the main target of this tutorial.
Picking up ammo
First, there are some needed variables in this tutorial.
Let’s create the function of added the picked up ammo to amount of ammo left.
When picked up ammo, it means no matter how many ammo left, player should be able to fire. Therefore, we need to set both bool as true. Then, add the picked up ammo amount.
Decrease ammo from magazine
Now we would create a method to calculate magazine ammo amount when firing.
In my game project, this method would be called when the gun object playing firing animation every time. This means the amount need to decrease 1 per shot.
Then this would check if the ammo amount of magazine is equal to 0, then player would not be able to fire again.
Reload from ammo left to magazine
This would be the main part of this function.
To reload the magazine, it is important to know the sum of ammo amount in magazine and ammo left.
If the sum is greater than the maximum amount of magazine, the ammo left should minus the result of maximum amount minus ammo amount of magazine.
Feel complicated? This can be understand as if there are still some ammo in your magazine, then your magazine should reloaded as the maximum ammo amount of a magazine, which is taking the insufficient ammo amount from ammo left.
On the other hand, if the sum is less than the maximum ammo amount of a magazine, then the ammo left should all be reloaded to magazine.
This would be easier to understand from code:
Check the bool again
The final part would be setting the bool “_canReload”.
When there is no more ammo left, this bool should be false. It would need to be checked every frame in Update().
And this is what I created to display both magazine ammo amount and ammo left.