- Home /
Increase audio pitch as object gets closer
I have this part in my enemy's script, that's supposed to increase it's AudioSource pitch as it gets closer to the player, and decrease it as it gets farther away. The problem is, it does the exact opposite. It increases the pitch as the enemy gets farther away, and decreases the pitch as the enemy gets closer... This seems like such an easy thing to fix, but no matter what I try, I just can't seem to figure out a way to do it. Here's that part of my script. I actually got it from someone answering a similar question in the past, only with speed rather than distance:
var p = Vector3.Distance (target.position, transform.position) / audioClipSpeed;
audio2.pitch = Mathf.Clamp( 1.3, 0.6, p); // p is clamped to sane values
My audioClipSpeed variable is set to 1.0, which is supposed to be the starting pitch. Can someone please tell me what's causing the code to do the exact opposite of what I need it to? Any help is appreciated.
Answer by avidesk · Sep 14, 2012 at 10:26 PM
A couple things I noticed: 1. If audioClipSpeed is 1 and doesn't change, it doesn't need to be there. 2. The value you want to clamp should be the first parameter, not the last. Also the lower limit is 2nd, upper limit 3rd.
Mathf.Clamp(p, 0.6, 1.3);
If you look at your code, distance is multiplied by pitch, so naturally as the distance increases the pitch will increase. To invert that, try this:
audio2.pitch = Mathf.Clamp((1 / p), 0.6, 1.3);
In this case, p equals distance between transforms.
Your answer
![](https://koobas.hobune.stream/wayback/20220613081048im_/https://answers.unity.com/themes/thub/images/avi.jpg)