Created
March 7, 2026 14:56
-
-
Save rob5300/4a04ba3cdd4236832bcf78b6a416c166 to your computer and use it in GitHub Desktop.
Unity Component to implement stereo audio panning in 2D
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| public class AudioPan2D : MonoBehaviour | |
| { | |
| [SerializeField] | |
| AudioSource audioSource; | |
| public Transform target; | |
| public float panRangeMax = 1f; | |
| private void Update() | |
| { | |
| if(audioSource == null || target == null) return; | |
| Vector2 dir = target.position - transform.position; | |
| float distance = dir.magnitude; | |
| dir.Normalize(); | |
| audioSource.panStereo = Vector2.Dot(Vector2.left, dir) * Mathf.Clamp01(distance / panRangeMax); | |
| } | |
| private void OnDrawGizmosSelected() | |
| { | |
| Gizmos.DrawWireSphere(transform.position, panRangeMax); | |
| } | |
| private void Reset() | |
| { | |
| audioSource = GetComponent<AudioSource>(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment