How can I create sound emmiters that pan and change volume based on distance from the player in a 2D game?
2 Answers
Use SoundEffect.CreateInstance();
to get a SoundEffectInstance
of your chosen sound effect.
You can then Play()
that instance while modifying its Volume
and Pan
properties.
Or, if it's a short, one-shot sound effect, you can simply use SoundEffect.Play(volume, pitch, pan);
to play it at your chosen volume and panning.
Here is some code that I have used in the past to set the volume and panning of a SoundEffectInstance
based on the emitting object's position and the camera:
public bool SetSoundForCamera(SoundEffectInstance sound, Vector2 position, float baseVolume)
{
Vector2 screenDistance = (position-cameraCenter) / cameraHalfSize;
float fade = MathHelper.Clamp(2f - screenDistance.Length(), 0, 1);
sound.Volume = fade * fade * baseVolume;
sound.Pan = MathHelper.Clamp(screenDistance.X, -1, 1);
return fade > 0;
}
For a SoundEffectInstance
, simply call that each frame while the sound is playing. You could extract the maths and use it for one-shot sounds as well.
Of course, for a 2D game, how quickly you pan and how quickly you fade out sounds as they go off screen will depend on your game. You should modify the maths to suit your own game's mood.
-
\$\begingroup\$ This is the easiest way to go if you're looking for just basic positioning. But if you want doppler, you're probably better off with the tutorial that The Communist Duck posted. Also, being able to setup 3d properties in the XACT authoring tool makes it really convenient to use. \$\endgroup\$ Mar 15, 2011 at 4:42
-
\$\begingroup\$ The downside to XACT (
Cue
instead ofSoundEffectInstance
) is that it doesn't work on Windows Phone. Of course, usingSoundEffectInstance.Apply3D
instead of mySetSoundForCamera
is fine too. \$\endgroup\$ Mar 15, 2011 at 8:08 -
\$\begingroup\$ I didn't realize there wasn't any XACT support for Windows Phone, that's a serious buzzkill. Good to have this bit of code around then, thanks for the followup! \$\endgroup\$ Mar 15, 2011 at 23:15
There is a 3D audio example on XNA's app hub. I'm pretty sure you can take the same concept for 2D.