facebook twitter hatena line email

「Unity/3d/collider/距離による音量変更」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(ページの作成:「<pre> using UnityEngine; public class SphereBgmTrigger : MonoBehaviour { [SerializeField] AudioSource audioSource; float maxDistance = 0f;// radius + 操作キャ...」)
 
(サンプル)
 
(同じ利用者による、間の1版が非表示)
行1: 行1:
 +
==サンプル==
 +
範囲内に入った際に、ある位置から離れると音量が下がる。
 +
 +
[[Unity/3d/collider/距離]] [ショートカット]
 +
 +
上記参考に、一部改変する。
 +
 
<pre>
 
<pre>
 
using UnityEngine;
 
using UnityEngine;

2022年4月22日 (金) 23:29時点における最新版

サンプル

範囲内に入った際に、ある位置から離れると音量が下がる。

Unity/3d/collider/距離 [ショートカット]

上記参考に、一部改変する。

using UnityEngine;
public class SphereBgmTrigger : MonoBehaviour
{
    [SerializeField] AudioSource audioSource;
    float maxDistance = 0f;// radius + 操作キャラ半径
    float maxVolumeRadius = 1f; // この半径範囲はmaxVolume
    // 範囲内に入ったとき
    void OnTriggerEnter(Collider collider)
    {
        Debug.Log("OnTriggerEnter");
        audioSource.Play();
        audioSource.loop = true;
        audioSource.volume = 0f;
        maxDistance = GetComponent<SphereCollider>().radius;
        Debug.Log("maxDistance=" + maxDistance);
    }
    // 範囲中のとき
    void OnTriggerStay(Collider collider)
    {
        Debug.Log("OnCollisionStay collision.gameObject.name=" + collider.gameObject.name);
        if (collider.gameObject.name == "CharacterSphere")
        {
            float distance = Vector3.Distance(transform.position, collider.gameObject.transform.position);
            distance -= collider.gameObject.GetComponent<SphereCollider>().radius;
            distance -= maxVolumeRadius;
            if (distance < 0)
            {
                distance = 0;
            }
            Debug.Log("distance=" + distance);
            float volume =  1 - (distance / (maxDistance - maxVolumeRadius));
            Debug.Log("volume=" + volume);
            audioSource.volume = volume;
        }
    }

    // 範囲から抜けたとき
    void OnTriggerExit(Collider collider)
    {
        audioSource.Stop();
        Debug.Log("OnTriggerExit");
    }
}