2023.12.22 오늘의 기록 3D 게임 숙련강의 사운드

2023. 12. 22. 20:39카테고리 없음

Audio Source 와 소리들을 넣어줄 스크립트를 작성해준다.

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Footsteps : MonoBehaviour
{
    public AudioClip[] footstepClips; //발소리를 넣어줄 배열을 만들어준다.
    private AudioSource audioSource;
    private Rigidbody _rigidbody;
    public float footstepThreshold;
    public float footstepRate;
    private float lasgFootstepTime;

    private void Start()
    {
        _rigidbody = GetComponent<Rigidbody>();
        audioSource = GetComponent<AudioSource>();
    }

    private void Update()
    {
        if(Mathf.Abs(_rigidbody.velocity.y) < 0.1f)
        {
            if(_rigidbody.velocity.magnitude > footstepThreshold)
            {
                if(Time.time - lasgFootstepTime > footstepRate)
                {
                    lasgFootstepTime =Time.time;
                    audioSource.PlayOneShot(footstepClips[Random.Range(0, footstepClips.Length)]);
                }
            }
        }
    }
}

 

Box Collider 를 사용하여 음악이 나오는 뮤직존을 만들어준다.

 

Is Trigger = 충돌감지는 하지만 충돌이 구현되지는 않는다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MusicZone : MonoBehaviour
{
    public AudioSource audioSource;
    public float fadeTime;
    public float maxVolume;
    private float targetVolume;

    private void Start()
    {
        targetVolume = 0.0f;
        audioSource = GetComponent<AudioSource>();
        audioSource.volume = targetVolume;
        audioSource.Play();

    }

    private void Update()
    {
        if(!Mathf.Approximately(audioSource.volume, targetVolume))
        {
            audioSource.volume = Mathf.MoveTowards(audioSource.volume, targetVolume, (maxVolume / fadeTime) * Time.deltaTime); 
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
            targetVolume = maxVolume;
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("Player"))
            targetVolume = 0.0f;
    }
}

 

 

스크립트와 오디오 소스를 이용하여 게임의 몰입도를 높여줄 음악을 추가할 수 있는데, 뮤직존을 활용하면 낮에는 평화로운 BGM을 밤에는 스산한 BGM을 사용하여 분위기의 전환을 할 수 있을 것 같다.

 

추가로 Camera를 추가하게 되면 자동적으로 Audio Listener가 생성되는데, 두 개 이상이 되지 않도록 주의한다.