In our space shooter game, the player can shoot as much as they want without an ammo limit and thus causes the game to be too easy since you can spam the fire button and move around giving enemies very little chance to defend themselves. In the Phase 1 Framework, we have another challenge to complete
Limit the lasers fired by the player to only 15 shots.
When the player is out of ammo, provide feedback through on-screen elements or sound effects. (ie: beep or ammo count displayed on screen.
Creating the UI
Since we needed to have visual feedback of how much ammo we have I chose to create the UI elements first.
I’ve used the Space Expansion UI Pack from kenney.nl. I’ve already imported and cut the sprites covered in an earlier article so I’ve gone ahead and created a new Image object in my Canvas and added the sprite I wanted to use. I’ve resized it to my needs and used a blue square button-like image and made it rectangular to represent the ammo. Since I could fit 19 thin objects into the parent object so my player will have 19 ammo instead of the suggested 15.
I always prefer creating the UI logic before implementing the actual logic. This allows me to update the UI when I’m ready to start testing my implementations and also fix what isn’t working as I’m reiterating and doing bug fixing. I’ve created a new public function called “UpdateAmmo” and in the curly brackets, I’ve added an int ammoCount which we’ll be referencing in our Player Script.
The logic of updating our ammo is very similar to that of our shield and therefore we need to refer to our ammo image and sprites in the same way.
Adding the Ammo Count
In our Player script, we have a Fire() function where the user can hold the shoot button in to fire off lasers repeatedly similarly to how a machine gun would fire. We’ll need to add a new integer variable to track how much ammo we have and to have a value to subtract from, and we’ll need to check if our ammo is greater than zero before the player can fire.
Under our Player Settings in my variables section, I’ve created a new private int and called it _ammoCount and assigned a value of 19. Then where we check for the input and to calculate the fire rate I also need to check if the _ammoCount is greater than 0, If that’s true (ie _ammoCount is 5) then the player can fire off shots. But we’ll also need to deduct one ammo every time a shot goes off to make sure the ammo does indeed become less. We’ll also need to update the UI here to give a visual representation of how much ammo is remaining.
And just like that, we have a system to fire off the lasers. I’ve removed the rest of the code where I instantiate the lasers to keep the scripts short and to the point but in that if function you can add your logic to fire off your lasers or anything else you want.