Implementing a Custom Doppler Effect System for Moving Sound Sources in Unity

Implementing a custom Doppler effect system in Unity allows developers to create more realistic audio experiences for moving sound sources. This guide provides a step-by-step approach to achieve this, enhancing immersion in your projects.

Understanding the Doppler Effect

The Doppler effect is the change in frequency or pitch of a sound wave as the source moves relative to the listener. When the source approaches, the pitch increases; when it recedes, the pitch decreases. Simulating this effect accurately in Unity requires modifying the audio pitch based on the relative velocity between the sound source and the listener.

Setting Up the Scene

Begin by creating a scene with a moving sound source and a listener. The sound source should have an AudioSource component, and the listener typically uses the built-in AudioListener component attached to the main camera or player object.

Creating the Custom Doppler Script

Next, create a new C# script named CustomDoppler and attach it to your sound source object. This script will calculate the relative velocity and adjust the pitch accordingly.

using UnityEngine;

public class CustomDoppler : MonoBehaviour
{
    public AudioSource audioSource;
    public Transform listenerTransform;
    public float dopplerFactor = 1.0f;

    private Vector3 lastPosition;

    void Start()
    {
        if (audioSource == null)
        {
            audioSource = GetComponent();
        }
        lastPosition = transform.position;
    }

    void Update()
    {
        Vector3 velocity = (transform.position - lastPosition) / Time.deltaTime;
        lastPosition = transform.position;

        Vector3 relativeVelocity = velocity - listenerTransform.GetComponent()?.velocity ?? Vector3.zero;

        float distance = Vector3.Distance(transform.position, listenerTransform.position);
        float speedAlongLine = Vector3.Dot(relativeVelocity, (listenerTransform.position - transform.position).normalized);

        float dopplerShift = (speedAlongLine / Mathf.Max(distance, 0.1f)) * dopplerFactor;

        audioSource.pitch = 1 + dopplerShift;
    }
}

Adjusting and Testing

Adjust the dopplerFactor parameter to control the intensity of the effect. Play the scene, move the sound source towards and away from the listener, and observe the pitch change. Fine-tune the script as needed for your specific setup.

Conclusion

By implementing this custom Doppler effect system, you gain more control over how sound behaves in your Unity projects. This enhances realism and immersion, especially in dynamic environments with moving objects and audio sources.