changing volume relative to the spherer collider center??!?

Hi ya’ll…lets see if i can express myself clear, English is not my native language so… xP.

I’m trying to write a script that when the bullet reaches a trigger it plays a sound…all good.
the tricky part is how can I change the volume of that sound relative to the center of the sphere collider. Say, if the bullet goes right into the center of the object plays at volume 1 and reduces it as it goes away from it. I’m in lack of math skills to do this.
this is what I have not working as I want though…

public var flyByBulletSounds : AudioClip[];
function OnTriggerEnter(hit : Collider){
	if(hit.collider.gameObject.tag == "SoundTrigger"){
		var randomSound : int = Random.Range(0, flyByBulletSounds.length - 1);
		var sphereCollider : SphereCollider =  hit.collider.gameObject.GetComponent("SphereCollider") as SphereCollider;
		
		hit.collider.audio.volume = Mathf.Clamp01(Vector3.Distance(this.gameObject.transform.position, sphereCollider.center));
		hit.collider.audio.clip = flyByBulletSounds[randomSound];
		hit.collider.audio.Play();
		Debug.Log("Bullet entered Trigger playing sound number : " + randomSound + " with Volume : " + hit.collider.audio.volume);
	}	
}

It always plays it at volume 1, because the distance is always the same as it reaches the trigger… what can I do?? Help plzzz

Why don't you use the inbuilt 3d sound for this? It has doppler effect and everything, is fully supported by the engine, and doesn't need any coding knowledge at all!

1 Answer

1

To answer your question: use OnTriggerStay() instead of OnTriggerEnter() - as the latter will only be called once (on entering) where the first one will be called continuously.

However I strongly advise you to set up the 3D sound settings of your audio component accordingly (Rolloff Mode, Min/Max distance), as all of the functionality you are trying to simulate is already built in! :slight_smile:

Cheers