Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / game

Day 15: Adding Shooting, Hit, and More Walking Sound Effects!

5.00/5 (2 votes)
10 Oct 2017CPOL3 min read 8.1K  
Adding shooting, hit, and more walking sound effects!

On Day 15, we’re going to continue adding more sound effects to our existing game, specifically the:

  • shooting sound effect
  • sound of the knight getting hit
  • player walking

Today is going to be a relatively short day, but let's get started!

Adding Enemy Hit Sounds

To start off, we’re going to do something like in Day 14. We’re going to create Audio Source Components in code and play the sound effects from there.

For shooting, we need to add our code to EnemyHealth:

C#
using UnityEngine;

public class EnemyHealth : MonoBehaviour
{
    public float Health = 100;
    public AudioClip[] HitSfxClips;
    public float HitSoundDelay = 0.5f;

    private Animator _animator;
    private AudioSource _audioSource;
    private float _hitTime;  

    void Start()
    {
        _animator = GetComponent<Animator>();
        _hitTime = 0f;
        SetupSound();
    }

    void Update()
    {
        _hitTime += Time.deltaTime;
    }
    
    public void TakeDamage(float damage)
    {
        if (Health <= 0) { return; } Health -= damage; if (_hitTime > HitSoundDelay)
        {
            PlayRandomHit();
            _hitTime = 0;
        }

        if (Health <= 0)
        {
            Death();
        } 
    }

    private void SetupSound()
    {
        _audioSource = gameObject.AddComponent<AudioSource>();
        _audioSource.volume = 0.2f;
    }

    private void PlayRandomHit()
    {
        int index = Random.Range(0, HitSfxClips.Length);
        _audioSource.clip = HitSfxClips[index];
        _audioSource.Play();
    }

    private void Death()
    {
        _animator.SetTrigger("Death");
    }
}

The flow of our new code is:

  1. We create our Audio Source component in SetupSound() called from Start()
  2. We don’t want to play the sound of the knight being hit every time we hit it, that’s why I set a _hitTime in Update() as a delay for the sound
  3. Whenever an enemy takes damage, we see if we’re still in a delay for our hit, if we’re not, we’ll play a random sound clip we added.

The code above should seem relatively familiar as we have seen it before in Day 14.

Once we have the code setup, the only thing left to do is to add the Audio clips that we want to use, which in this case is Male_Hurt_01Male_Hurt_04.

That’s about it. If we were to shoot the enemy now, they would make damage hits.

Player Shooting Sounds

The next sound effect that we want to add is the sound of our shooting. To do that, we’re going to make similar adjustments to the PlayerShootingController.

C#
using UnityEngine;

public class PlayerShootingController : MonoBehaviour
{
    public float Range = 100;
    public float ShootingDelay = 0.1f;
    public AudioClip ShotSfxClips;

    private Camera _camera;
    private ParticleSystem _particle;
    private LayerMask _shootableMask;
    private float _timer;
    private AudioSource _audioSource;

    void Start () {
        _camera = Camera.main;
        _particle = GetComponentInChildren<ParticleSystem>();
        Cursor.lockState = CursorLockMode.Locked;
        _shootableMask = LayerMask.GetMask("Shootable");
        _timer = 0;
           SetupSound();
    }
    
    void Update ()
    {
        _timer += Time.deltaTime;

        if (Input.GetMouseButton(0) && _timer >= ShootingDelay)
        {
            Shoot();
        }
           else if (!Input.GetMouseButton(0))
        {
            _audioSource.Stop();
        }
    }

    private void Shoot()
    {
        _timer = 0;
        Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit = new RaycastHit();
        _audioSource.Play();

        if (Physics.Raycast(ray, out hit, Range, _shootableMask))
        {
            print("hit " + hit.collider.gameObject);
            _particle.Play();

            EnemyHealth health = hit.collider.GetComponent<EnemyHealth>();
            EnemyMovement enemyMovement = hit.collider.GetComponent<EnemyMovement>();
            if (enemyMovement != null)
            {
                enemyMovement.KnockBack();
            }
            if (health != null)
            {
                health.TakeDamage(1);
            }
        }
    }

    private void SetupSound()
    {
        _audioSource = gameObject.AddComponent<AudioSource>();
        _audioSource.volume = 0.2f;
        _audioSource.clip = ShotSfxClips;
    }
}

The flow of the code is like the previous ones, however for our gun, I decided that I want to use the machine gun sound instead of individual pistol shooting.

  1. We still setup our Audio Component code in Start().
  2. The interesting part is that in Update(), we play our Audio in Shoot() and as long as we’re holding down the mouse button, we’ll continue playing the shooting sound and when we let go, we would stop the audio.

After we added our script, we attach Machine_Gunfire_01 to the script component.

Player Walking Sound

Last but not least, we’re going to add the player walking sound in our PlayerController component.

C#
using UnityEngine;

public class PlayerController : MonoBehaviour {

    public float Speed = 3f;
    public AudioClip[] WalkingClips;
    public float WalkingDelay = 0.3f;

    private Vector3 _movement;
    private Rigidbody _playerRigidBody;
    private AudioSource _walkingAudioSource;
    private float _timer;

    private void Awake()
    {
        _playerRigidBody = GetComponent<Rigidbody>();
        _timer = 0f;
        SetupSound();
    }

    private void SetupSound()
    {
        _walkingAudioSource = gameObject.AddComponent<AudioSource>();
        _walkingAudioSource.volume = 0.8f;
    }

    private void FixedUpdate()
    {
        _timer += Time.deltaTime;
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        if (horizontal != 0f || vertical != 0f)
        {
            Move(horizontal, vertical);
        }
    }

    private void Move(float horizontal, float vertical)
    {
        if (_timer >= WalkingDelay)
        {
             PlayRandomFootstep();
            _timer = 0f;
        }
        _movement = (vertical * transform.forward) + (horizontal* transform.right);
        _movement = _movement.normalized * Speed * Time.deltaTime;
        _playerRigidBody.MovePosition(transform.position + _movement);
    }

    private void PlayRandomFootstep()
    {
        int index = Random.Range(0, WalkingClips.Length);
        _walkingAudioSource.clip = WalkingClips[index];
        _walkingAudioSource.Play();
    }
}

Explanation

This code is like what we’ve seen before, but there were some changes made.

  1. As usual, we create the sound component in Start() and a walking sound delay.
  2. In Update(), we made some changes. We don’t want to play our walking sound whenever we can. We only want to play it when we’re walking. To do this, I added a check to see if we’re moving before playing our sound in Move().

Also, notice that the audio sound is 0.8 as opposed to our other sounds. We want our sound to be louder than the other players so we can tell the difference between the player walking and the enemy.

After writing the script, we don’t forget to add the sound clips. In this case, I just re-used our footsteps by using Footstep01Footstep04.

Conclusion

I’m going to call it quits for today for Day 15!

Today, we added more gameplay sound into the game so when we play, we have a more complete experience.

I’m concerned about what happens when we have more enemies and how that would affect the game, but that’ll be for a different day!

Day 14 | 100 Days of VR | Day 16

Home

The post Day 15: Adding Shooting, Hit, and More Walking Sound Effects! appeared first on Coding Chronicles.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)