Unityで衝突の強さによって音量を変える
衝突したときの音を衝突の強さによって変えてみます。
Sphereのプレハブと音声を用意します。
SphereにはコライダーとRigidbodyがついています。
Planeで段差を作って一番上にCubeを置きました。
Sphereを発射させる位置に空のゲームオブジェクトを起きます。
空のゲームオブジェクトにスクリプトを付けます。
このスクリプトで、Fキーを押すとSphereがCubeに向かって発射されるようにします。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShootScript : MonoBehaviour
{
    public GameObject sphere;
    // Start is called before the first frame update
    void Start()
    {
        
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            Rigidbody rb_sphere = Instantiate(sphere, transform.position, transform.rotation).GetComponent<Rigidbody>();
            rb_sphere.AddForce(-transform.right * 30f, ForceMode.Impulse);
        }
    }
}
CubeにはコラーダーとRigidbody、Audio Source、新規スクリプトを付けました。
Audio SourceのAudioClipに音声をアタッチして、Play On Awakeのチェックを外します。Spatial Blendのスライダーを3Dにすると、音を受け取るAudio Listenerのついたオブジェクトと音源との距離によって音量が変わるのでまずは2Dにします。
Cubeのスクリプトでは衝突のインパルスのベクトルの長さを調べて、0~1の間の値にして、それをAudioSourceの音量にしています。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeSoundScript : MonoBehaviour
{
    AudioSource audio;
    // Start is called before the first frame update
    void Start()
    {
        audio = GetComponent<AudioSource>();
    }
    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnCollisionEnter(Collision collision)
    {
        float i = collision.impulse.magnitude / 15f;
        if (i > 1) i = 1;      
        audio.volume = i;
        audio.Play();
        Debug.Log(collision.impulse.magnitude + " " + audio.volume);
    }
}
collision.impulse が衝突のインパルスで、magnitudeでそのベクトルの長さが返ります。0~1の値になるように、適当な値で割っています。
音量を変更するには、AudioSource.volume に0~1のfloat値を入れます。
衝突のインパルスのベクトルの長さと音量をコンソールに表示させています。
Cubeの衝突の強さによって音量が変わっています。
CubeのAudio SourceコンポーネントのSpatial Blendを3Dにしてみます。
メインカメラがCubeから離れている分聞こえにくいですが、衝突によって音量が変わっているのがわかると思います。
