Arg… the loop (part 2)

I didn’t realise how much effort looping the map was going to be. I’ve still got visible tearing and shadow issues at the edges and now an – albeit minor – audio problem. Unity comes with a great method for playing audio at the correct volume based on the distance between the listener and the audio source. It’s built in! But all that goes out of the window with a looped level. ugh. For example; If the player (listener) is close to one edge of the map and an explosion happens at the opposite end of the map the built in method won’t play the sound (or play it very quietly) as the player and explosion appear – to Unity – to be far apart. Only they aren’t. In the looped view they are side by side.

To handle this I’ve had to write my own simple audio controller to adjust sounds that would be affected by the loop. Essentially any sound that needs it’s volume adjusted based on the perceived (not actual) distance from the player.

public void GroundExplosion(Vector3 position) {
    //Select a random explosion sound from an array of sound clips
    AudioClip boom = groundExplosions[Random.Range(0, groundExplosions.Length)];
    audioPlayer.PlayOneShot(boom, VolumeToPlay(position));
}

private float VolumeToPlay(Vector3 position) {
    //Get the distance on Z between the objects
    float distance = Mathf.Abs(player.transform.position.z - position.z);

    //Is the distance greater than the half length of the map?
    if (distance > (map.length / 2)) {

        //Remove the excess (i.e. get the excess above the half and remove from the Distance)
        distance = Mathf.Abs(distance - map.length);
    }
        
    //Return a value (Between 0 and 1) based on the max distance, closest distance, current distance)
    return Mathf.InverseLerp(map.length / 2, 0, distance);
}

My audio controller is handling quite a number of different sounds and I only need to worry about distance on the Z axis, but hopefully this is enough to show how it’s managing it. I wonder what “the loop” will throw at me next. Cheers, J

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.