2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Unity】指向性スピーカーの実装例

Last updated at Posted at 2024-03-09

AudioSource の向きで音量や聞こえる距離が変わるコンポーネントを作りました。
AudioSource が AudioListener に向くほど、大きく遠くまで聞こえるようになります。
声やスピーカーにご利用ください。

DirectionalAudioSource.cs
using UnityEngine;

public class DirectionalAudioSource : MonoBehaviour
{
    [SerializeField] private AudioSource audioSource;
    [SerializeField] private Transform audioSourceTransform;
    [SerializeField] private Transform listenerTransform;
    [SerializeField] private AnimationCurve curve = new AnimationCurve(new Keyframe[2] { new Keyframe(0f, 0f), new Keyframe(1f, 1f) });
    [SerializeField, Range(0f, 1f)] private float minVolume = 0.25f;
    [SerializeField, Range(0f, 1f)] private float maxVolume = 1f;

    private float maxDistance;


    private void Start()
    {
        maxDistance = audioSource.maxDistance;
    }
    void Update()
    {
        if (listenerTransform == null && FindAudioListener()) return;
        UpdateVolume();
    }

    public void UpdateVolume()
    {
        var volume = Mathf.LerpUnclamped(minVolume, maxVolume, curve.Evaluate(GetVolume()));
        audioSource.maxDistance = volume * maxDistance;
        audioSource.volume = volume;
    }
    private float GetVolume() => Vector3.Dot(audioSourceTransform.forward, (listenerTransform.position - audioSourceTransform.position).normalized) * 0.5f + 0.5f;
    
    public void SetAudioListener(AudioListener audioListener) => listenerTransform = audioListener.transform;
    public bool FindAudioListener()
    {
        var listener = FindObjectOfType<AudioListener>();
        if (listener == null) return false;
        listenerTransform = listener.transform;
        return true;
    }
    
#if UNITY_EDITOR
    private void OnValidate()
    {
        if (audioSource == null)
        {
            audioSource = GetComponent<AudioSource>();
            if (audioSource != null) audioSourceTransform = audioSource.transform;
        }
    }
#endif
}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?