Jump to content
  • Advertisement
  • entries
    44
  • comments
    19
  • views
    2419

100 Days of VR: Day 18 Creating Weapon Ammo in Unity

Josh Chang

573 views

Today in Day 18, we’re going to start adding UI components into our game!

2 days ago, on Day 16, we created a reload system and just yesterday we started shooting lasers at enemies, now would be the perfect time to create a reload system and some UI to display our reload.

While we’re at it, we might as well make some other UI fixes. Here are the things that we’re going to tackle today:

  • Create the reload system and UI

The first thing that needs to be done is to create the reload system.

Without any delays, let’s get started!

Creating the Reload System

There are 2 things that need to be done for us to have a reload system. The first part is the UI that shows how many ammos we have and the second is the code that will manage it.

Let’s create the UI system first.

Player Ammo UI

First thing to do, let’s find a motivation to for our UI.

For my source of inspiration, I’m going to use Overwatch, which I think is pretty common these days:

 
0*Ka2hf9ALShsDqgc5.jpg

The basic thing is that the HP is on the bottom left corner and the ammo is on the bottom right.

Let’s get started creating the ammo UI. In the hierarchy pane, right click and under UI select Text. We’re going to call it Ammo.

As you might recall, when we do this, Unity automatically creates a Canvas screen for us. In this case, we already have one that called HUD.

To work with our UI, make sure to hit 2D button right below the Scene tab.

 
0*ItATTM3OyBH5YZrI.png

Let’s adjust the text to be at the bottom right corner of our screen.

Select Ammo and under the Rect Transform component, select the anchor presets square and while holding Shift + Alt, select bottom right, to move our text to the bottom right corner.

It’s also kind of small, so let’s change the size a bit too:

  • Width: 160
  • Height: 60
  • Text Size: 24
  • Font Style: Bold
  • Text: 30/30
  • Color: White

Here’s what we’ll see now if we pull up our game tab:

 
0*AsWLT8-q6IdfuUDL.png

Now that we have our initial setup let’s write code!

Ammo and Reload Code

We have the UI, now it’s time to write some code for reloading and ammo!

We’ll be changing our PlayerShootingController, here’s the code:

 
using UnityEngine;
using System.Collections;
public class PlayerShootingController : MonoBehaviour
{
    public float Range = 100;
    public float ShootingDelay = 0.1f;
    public AudioClip ShotSfxClips;
    public Transform GunEndPoint;
    public float MaxAmmo = 10f;
    private Camera _camera;
    private ParticleSystem _particle;
    private LayerMask _shootableMask;
    private float _timer;
    private AudioSource _audioSource;
    private Animator _animator;
    private bool _isShooting;
    private bool _isReloading;
    private LineRenderer _lineRenderer;
    private float _currentAmmo;

    void Start () {
        _camera = Camera.main;
        _particle = GetComponentInChildren<ParticleSystem>();
        Cursor.lockState = CursorLockMode.Locked;
        _shootableMask = LayerMask.GetMask("Shootable");
        _timer = 0;
        SetupSound();
        _animator = GetComponent<Animator>();
        _isShooting = false;
        _isReloading = false;
        _lineRenderer = GetComponent<LineRenderer>();
        _currentAmmo = MaxAmmo;
    }
    
    void Update ()
    {
        _timer += Time.deltaTime;
        // Create a vector at the center of our camera's viewport
        Vector3 lineOrigin = _camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.0f));
        // Draw a line in the Scene View  from the point lineOrigin in the direction of fpsCam.transform.forward * weaponRange, using the color green
        Debug.DrawRay(lineOrigin, _camera.transform.forward * Range, Color.green);
        if (Input.GetMouseButton(0) && _timer >= ShootingDelay && !_isReloading && _currentAmmo > 0)
        {
            Shoot();
            if (!_isShooting)
            {
                TriggerShootingAnimation();
            }
        }
        else if (!Input.GetMouseButton(0))
        {
            StopShooting();
            if (_isShooting)
            {
                TriggerShootingAnimation();
            }
        }
        if (Input.GetKeyDown(KeyCode.R))
        {
            StartReloading();
        }
    }
    private void StartReloading()
    {
        _animator.SetTrigger("DoReload");
        StopShooting();
        _isShooting = false;
        _isReloading = true;
    }
    private void TriggerShootingAnimation()
    {
        _isShooting = !_isShooting;
        _animator.SetTrigger("Shoot");
    }
    private void StopShooting()
    {
        _audioSource.Stop();
        _particle.Stop();
    }
    private void Shoot()
    {
        _timer = 0;
        Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit = new RaycastHit();
        _audioSource.Play();
        _particle.Play();
        _currentAmmo--;
        _lineRenderer.SetPosition(0, GunEndPoint.position);
        StartCoroutine(FireLine());
        if (Physics.Raycast(ray, out hit, Range, _shootableMask))
        {
            print("hit " + hit.collider.gameObject);
            _lineRenderer.SetPosition(1, hit.point);
            EnemyHealth health = hit.collider.GetComponent<EnemyHealth>();
            EnemyMovement enemyMovement = hit.collider.GetComponent<EnemyMovement>();
            if (enemyMovement != null)
            {
                enemyMovement.KnockBack();
            }
            if (health != null)
            {
                health.TakeDamage(1);
            }
        }
        else
        {
            _lineRenderer.SetPosition(1, ray.GetPoint(Range));
        }
    }
    private IEnumerator FireLine()
    {
        _lineRenderer.enabled = true;
        yield return ShootingDelay - 0.05f;
        _lineRenderer.enabled = false;
    }
    // called from the animation finished
    public void ReloadFinish()
    {
        _isReloading = false;
        _currentAmmo = MaxAmmo;
    }
    private void SetupSound()
    {
        _audioSource = gameObject.AddComponent<AudioSource>();
        _audioSource.volume = 0.2f;
        _audioSource.clip = ShotSfxClips;
    }
}
 

The code flow for this is straightforward:

  1. We made 2 new variables MaxAmmo and _currentAmmo to represent how many bullets we have left to shoot.
  2. In Start() we initialize our current ammo amount.
  3. Whenever we shoot, we make sure that our ammo is above 0 otherwise we can’t shoot and then we decrement our _currentAmmo count.
  4. When we finish reloading, we’ll restore our ammo to max.

With the code, we have one problem, while we’re shooting, if we never let go of our mouse, we’ll continue to play the shooting animation and sound effect. We need to change this.

I fixed the problem by adding another check to make sure that we stop shooting when we either let go of our mouse or when we run out of bullets.

Here’s the change we did for Update():

   
  void Update ()
    {
        _timer += Time.deltaTime;
        // Create a vector at the center of our camera's viewport
        Vector3 lineOrigin = _camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.0f));
        // Draw a line in the Scene View  from the point lineOrigin in the direction of fpsCam.transform.forward * weaponRange, using the color green
        Debug.DrawRay(lineOrigin, _camera.transform.forward * Range, Color.green);
        if (Input.GetMouseButton(0) && _timer >= ShootingDelay && !_isReloading && _currentAmmo > 0)
        {
            Shoot();
            if (!_isShooting)
            {
                TriggerShootingAnimation();
            }
        }
        else if (!Input.GetMouseButton(0) || _currentAmmo <= 0)
        {
            StopShooting();
            if (_isShooting)
            {
                TriggerShootingAnimation();
            }
        }
        if (Input.GetKeyDown(KeyCode.R))
        {
            StartReloading();
        }
    }
 

Now that we have the script for reloading and shooting, we need to add our shooting mechanisms.

The first thing we’re going to do is to go to our original HUD component that we created in Day 10 and create a new script called ScreenManager.

The script will be used for ammo and later score count, and in the future health. Here’s our code:

 
using UnityEngine;
using UnityEngine.UI;
public class ScreenManager : MonoBehaviour
{
    public Text AmmoText;
    void Start()
    {
        {
            PlayerShootingController shootingController = Camera.main.GetComponentInChildren<PlayerShootingController>();
            UpdateAmmoText(shootingController.MaxAmmo, shootingController.MaxAmmo);
        }
    }
    public void UpdateAmmoText(float currentAmmo, float maxAmmo)
    {
        AmmoText.text = currentAmmo + "/" + maxAmmo;
    }
}
 

Here’s how our code works:

  1. We take in the Text game object that we use for ammo.
  2. In Start() we initialize our text ammo by getting our PlayerShootingController that’s a child of our camera and using the max ammo value we set
  3. Inside UpdateAmmoText() we give it the ammo amount to print out. I made this public, because we want to call this function from elsewhere.

There was a design decision that I was thinking of as I was going through this.

I was looking back at the score UI that was made for the Survival Shooter tutorial and it used static variables to represent the score. Static meaning you can access is anywhere, anytime without needing access to the script itself.

That worked in the context that only the manager needed to know anything about the score, however in our case, we already have our ammo amount in our PlayerShootingController, so if that’s the case, there’s no need to keep a separate instance to keep track of our ammo amount.

Instead let’s just pass in the values that we want the text to print out.

Another benefit of this is that we don’t have to re-render our text every single time we call Update() and we only change it when we need to.

The only downside is that we must get an instance of ScreenManagerwhenever we want to make any changes as opposed to the static method that was used in the tutorial.

Updating our PlayerShootingController, here’s what we get:

 
using UnityEngine;
using System.Collections;
public class PlayerShootingController : MonoBehaviour
{
    public float Range = 100;
    public float ShootingDelay = 0.1f;
    public AudioClip ShotSfxClips;
    public Transform GunEndPoint;
    public float MaxAmmo = 10f;
    private Camera _camera;
    private ParticleSystem _particle;
    private LayerMask _shootableMask;
    private float _timer;
    private AudioSource _audioSource;
    private Animator _animator;
    private bool _isShooting;
    private bool _isReloading;
    private LineRenderer _lineRenderer;
    private float _currentAmmo;
    private ScreenManager _screenManager;

    void Start () {
        _camera = Camera.main;
        _particle = GetComponentInChildren<ParticleSystem>();
        Cursor.lockState = CursorLockMode.Locked;
        _shootableMask = LayerMask.GetMask("Shootable");
        _timer = 0;
        SetupSound();
        _animator = GetComponent<Animator>();
        _isShooting = false;
        _isReloading = false;
        _lineRenderer = GetComponent<LineRenderer>();
        _currentAmmo = MaxAmmo;
        _screenManager = GameObject.FindWithTag("ScreenManager").GetComponent<ScreenManager>();
    }
    
    void Update ()
    {
        _timer += Time.deltaTime;
        // Create a vector at the center of our camera's viewport
        Vector3 lineOrigin = _camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.0f));
        // Draw a line in the Scene View  from the point lineOrigin in the direction of fpsCam.transform.forward * weaponRange, using the color green
        Debug.DrawRay(lineOrigin, _camera.transform.forward * Range, Color.green);
        if (Input.GetMouseButton(0) && _timer >= ShootingDelay && !_isReloading && _currentAmmo > 0)
        {
            Shoot();
            if (!_isShooting)
            {
                TriggerShootingAnimation();
            }
        }
        else if (!Input.GetMouseButton(0) || _currentAmmo <= 0)
        {
            StopShooting();
            if (_isShooting)
            {
                TriggerShootingAnimation();
            }
        }
        if (Input.GetKeyDown(KeyCode.R))
        {
            StartReloading();
        }
    }
    private void StartReloading()
    {
        _animator.SetTrigger("DoReload");
        StopShooting();
        _isShooting = false;
        _isReloading = true;
    }
    private void TriggerShootingAnimation()
    {
        _isShooting = !_isShooting;
        _animator.SetTrigger("Shoot");
    }
    private void StopShooting()
    {
        _audioSource.Stop();
        _particle.Stop();
    }
    private void Shoot()
    {
        _timer = 0;
        Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit = new RaycastHit();
        _audioSource.Play();
        _particle.Play();
        _currentAmmo--;
        _screenManager.UpdateAmmoText(_currentAmmo, MaxAmmo);
        _lineRenderer.SetPosition(0, GunEndPoint.position);
        StartCoroutine(FireLine());
        if (Physics.Raycast(ray, out hit, Range, _shootableMask))
        {
            print("hit " + hit.collider.gameObject);
            _lineRenderer.SetPosition(1, hit.point);
            EnemyHealth health = hit.collider.GetComponent<EnemyHealth>();
            EnemyMovement enemyMovement = hit.collider.GetComponent<EnemyMovement>();
            if (enemyMovement != null)
            {
                enemyMovement.KnockBack();
            }
            if (health != null)
            {
                health.TakeDamage(1);
            }
        }
        else
        {
            _lineRenderer.SetPosition(1, ray.GetPoint(Range));
        }
    }
    private IEnumerator FireLine()
    {
        _lineRenderer.enabled = true;
        yield return ShootingDelay - 0.05f;
        _lineRenderer.enabled = false;
    }
    // called from the animation finished
    public void ReloadFinish()
    {
        _isReloading = false;
        _currentAmmo = MaxAmmo;
        _screenManager.UpdateAmmoText(_currentAmmo, MaxAmmo);
    }
    private void SetupSound()
    {
        _audioSource = gameObject.AddComponent<AudioSource>();
        _audioSource.volume = 0.2f;
        _audioSource.clip = ShotSfxClips;
    }
}
 

Here’s what we did:

  1. We looked for our ScreenManager by looking for it via a tag we set on it called ScreenManager.
  2. Any time we change our ammo amount we would call UpdateAmmoText() in our _screenManager. In this case, there are 2 places: after we shoot and after we reload.

Now before we try our game, first go to our HUD game object that we attached our ScreenManager script to, and create a new Tag called ScreenManager and make that the Tag for HUD.

If we were to play the game now, you’ll see that when we shoot, our ammo goes down, and when we hit R to reload, it goes back up to our maximum amount!

 
0*51w3MiBsIBfFqdSk.png

Conclusion

That’s it for today! I thought I would get to do more, but it looks like that was not the case for me!

To recap everything we did today, we created an ammo system where after we shoot all of our bullets we have to reload.

Afterwards we create a new Text that represent our ammo count on the bottom right hand corner of the screen.

I think tomorrow on Day 19, we’ll continue to add more pieces of the game like player health and a scoring system.

Source: Day 18

Visit the 100 Days of Unity VR Development main page.

Visit our Homepage



0 Comments


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement
  • Advertisement
  • Blog Entries

  • Similar Content

    • By MiTi
      Dear everyone, this is my newest game, please check out and give me feedback. Thanks for your consideration.

      Overview: Cross n Puzz is a creative and addicting word puzzle game. It not only challenges your brain but also improve memory and other types of cognitive function.

      For IOS: https://itunes.apple.com/app/crossword-puzzle-image/id1435575074

      For Android: https://play.google.com/store/apps/details?id=com.caag.crosswordnpuzzle

      Game trailer: https://www.youtube.com/watch?v=stNuktpJH44&feature=youtu.be
      Crossword Puzzle Image Trailer Official.mp4  
    • By KevDev
      A Unity Asset for customizable lowpoly weapons and shields.
      - Full Version: http://u3d.as/1hvG
      - Free Version: http://u3d.as/1jZV
      You can get the character model used in the video here (for FREE!): http://u3d.as/1kP7
       

      View full story
    • By KevDev
      A Unity Asset for customizable lowpoly weapons and shields.
      - Full Version: http://u3d.as/1hvG
      - Free Version: http://u3d.as/1jZV
      You can get the character model used in the video here (for FREE!): http://u3d.as/1kP7
       
    • By KevDev
      [UNITY ASSET]
      Customizable lowpoly weapons and shields.
      - Full Version: http://u3d.as/1hvG
      - Free Version: http://u3d.as/1jZV
      You can get the character model used in the video here (for FREE!): http://u3d.as/1kP7
       
    • By mtjscott
      Hey, so i've created a disk in unity (2D mobile) that will be shot forward if you drag it back and the further you drag it from the start point the more force will be applied to the impulse similar to the 8ball pool drag to shoot mechanic on miniclip. However, when I applied a script that allows the main camera to follow the ball it broke the mechanic since the balls position is calculated through the camera in world space. So I created a bool that locks the camera in place until the ball is released so the calculation would happen before the camera starts to move. This works however the ball now rubber bands back and forwards close to the start position.
       
      If anything needs more explaining then i'd be glad to do so. I've only been coding for about a week so you'll have to bare with me. Any help is appreciated. Thank you very much.
       
      Here's What happens:
      https://gyazo.com/f211e50f32ac59437a93dad7295a14be
      (screencap gif of the game viewer)
       
      Here is the shoot script:
      using System.Collections; using System.Collections.Generic; using UnityEngine; public class Shoot : MonoBehaviour { [SerializeField] GameObject Disc; [SerializeField] float multiplier; Vector3 initPos; private Rigidbody2D rb; public static bool ballIsReleased = false; bool recordingDistanceDragged = false; private void Start() { rb = gameObject.GetComponent<Rigidbody2D>(); initPos = transform.position; } void OnMouseDrag() { recordingDistanceDragged = true; if(recordingDistanceDragged == true) { transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10)); } else { transform.position = initPos; } } void OnMouseUp() { ballIsReleased = true; } private void FixedUpdate() { if(ballIsReleased == true) { rb.AddForce((initPos - transform.position) * multiplier, ForceMode2D.Impulse); Debug.Log("ball is released"); recordingDistanceDragged = false; } else { ballIsReleased = false; } } }  
      Here is the camera follow script:
      using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraFollow : MonoBehaviour { private Vector2 velocity; public float smoothTimeY; public float smoothTimeX; public GameObject player; private void Start() { player = GameObject.FindGameObjectWithTag("Player"); } private void FixedUpdate() { if (Shoot.ballIsReleased == true) { Debug.Log("camera can move"); float posX = Mathf.SmoothDamp(transform.position.x, player.transform.position.x, ref velocity.x, smoothTimeX); float posY = Mathf.SmoothDamp(transform.position.y, player.transform.position.y, ref velocity.y, smoothTimeY); transform.position = new Vector3(posX, posY, transform.position.z); } } }  
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!