So I’m working on a music system that increases the volume of the track the closer you get to an item. The only problem is that Vector3.distance returns a large float and volume takes 0 to 1.

What can I use to make my float read 0 if it’s too far away and 1 if the player is on top of the target? I am sure there is a Mathf function that does exactly this but I have no clue what it is.

Cheers!

The first thing to define is a value for “on target”. This could be a distance of zero, or another value such that any distance less means on target and will result in a volume of 1.

Similarly, define “too far away” as a value beyond which any distance will always have no volume.

Once those two limits are defined, the volume itself is a percentage calculation.

```
float onTarget = 0f;
float tooFar = 100f;
float range = tooFar - onTarget;
float distance = Mathf.Min(Mathf.Max(Vector3.Distance(a.position, b.position), onTarget), tooFar) - onTarget;
float volume = (range - distance) / range;
```

first clamp to a max value then divide by the max. so lets say your max distance to hear anything is 500

```
max_hear_range = 500;
distance = //distance check
mathf.clamp (distance, 0, max_hear_range)
so now your certain to get only 0 to 500.
```

then

```
audiodistance = distance/ max_hear_range;
```

so now you have a value between 0 and 1. The only problem is you actaully need the inverse basically, you want something 499 to be just above absolute zero not nearly 1 which is what 499/500 is so now you need to inverse it basically.

```
audiodistance = 1 - audiodistance;
```

now if they are currently at full volume which is what max distance would produce it will substact it all and give you nothing. if they are at a distance of 1 on the other hand. 1/500 gives you .002 and 1 - .002 is nearly 1 and so max volume basically.

you’ve now successfully given the volume a min and max range, interpolated it between one and zero and inversed it. yay!