How does one code an audio rolloff along the x axis?
My 2D game requires a sound to have the same volume along the y axis, but a different volume depending on the distance to the camera on the x axis. I can't figure out how to code the last part of the script though, can you help me? The volume should stay at 0 until the distance is equal/smaller than MinDist at which point the volume should grow linearly until the distance is equeal/smaller than MinDist.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spatialFader : MonoBehaviour
{
private float pos;
private float pos_other;
private float dist;
private AudioSource source;
public float MinDist;
public float MaxDist;
private float sqrMinDist;
private float sqrMaxDist;
void Start ()
{
source = GetComponent<AudioSource> ();
sqrMinDist = MinDist * MinDist;
sqrMaxDist = MaxDist * MaxDist;
}
void Update () {
pos_other = GameObject.Find("Main Camera").transform.position.x;
pos = transform.position.x;
dist = pos - pos_other;
print("Distance to other: " + dist);
//this is the part where I don't know what to do anymore:
var t =
source.volume = Mathf.Lerp(0,1,t);
}
}
Comment
Answer by TobiKnitt · Feb 15, 2018 at 05:50 PM
I found a solution! Not what I originally had in mind, but for what I'm doing it works fine. At a certain distance it just fades in or out over time.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
public class SoundRolloff : MonoBehaviour {
private AudioSource source;
public float spatialBlend;
public float minDistance;
public float maxDistance;
public float fadeDistance;
public float volume;
private float pos;
private float pos_other;
private float dist;
private float currentVolume;
// Use this for initialization
void Start () {
source = GetComponent<AudioSource> ();
source.volume = 0;
currentVolume = source.volume;
}
// Update is called once per frame
void Update () {
source = GetComponent<AudioSource> ();
source.spatialBlend = spatialBlend;
source.minDistance = minDistance;
source.maxDistance = maxDistance;
source.dopplerLevel = 0;
source.spread = 0;
pos_other = GameObject.Find("Main Camera").transform.position.x;
pos = transform.position.x;
dist = pos - pos_other;
if (dist < 0) {
dist = -dist * 2;
}
if (dist > fadeDistance){
source.volume -= volume * Time.deltaTime;
}
if ((dist < fadeDistance) && source.volume < volume) {
source.volume += volume * Time.deltaTime;
}
}
}