public void PlaySound(string soundName, float screenWidth, float screenHeight, Vector2?soundSource = null) { // If the music crashed, try to restart it. if (MusicCrashed) { MusicCrashed = false; PlayMusic(MusicNameWhenCrashed); } try { SoundEffect effect = Content.Load <SoundEffect>(soundName); if (soundSource == null) { effect.Play(1f, 0f, 0f); } else { // f(x) = -x/2000 + 1 Vector2 target = GameLibHelper.ToVector2(CameraService.GetTarget(screenWidth, screenHeight)); float volume = -(float)Math.Sqrt((target.X - soundSource.Value.X) * (target.X - soundSource.Value.X) + (target.Y - soundSource.Value.Y) * (target.Y - soundSource.Value.Y)) / 1000 + 1; volume = Math.Max(volume, 0); effect.Play(volume, 0f, 0f); } } catch (Exception) { } }