Playing audio is great, but not everyone wants audio playing all the time. Platforms like MacOS have poor control for per-application sound levels so we should empower the people playing our games with the ability to control how much sound the game makes.
To do this we’ll start to build out the Settings
Menu.
We already have a button for Settings
although it doesn’t do anything yet.
In lib.rs
we’ll create a new mod for settings and a new settings.rs
file.
pub mod assets;
pub mod board;
pub mod colors;
pub mod controls;
pub mod food;
pub mod settings;
pub mod snake;
pub mod ui;
We’ll start up with audio settings, although later we’ll add more settings here as well. Create a SettingsPlugin
like we have for other sub-modules as well.
We’re choosing to make AudioSettings
an enum rather than a boolean because this makes it more clear in the API surface what is actually happening. It also gives us room in the future to offer different levels of audio options.
use bevy::prelude::*;
pub struct SettingsPlugin;
impl Plugin for SettingsPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<GameSettings>();
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AudioSettings {
ON,
OFF,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GameSettings {
pub audio: AudioSettings,
}
impl Default for GameSettings {
fn default() -> Self {
GameSettings {
audio: AudioSettings::ON,
}
}
}
Then in main.rs
we’ll add the SettingsPlugin
to our game.
.add_plugins(DefaultPlugins)
.add_plugin(AudioPlugin)
.add_plugin(SettingsPlugin)
.add_plugin(ControlsPlugin)
Settings don’t do anything if we don’t use them, so in tick
add GameSettings
to the arguments.
pub fn tick(
...
sounds: Res<AudioAssets>,
settings: Res<GameSettings>,
) {
and we can use this resource to conditionally play the audio by checking to see if the user has turned audio on first.
if settings.audio == AudioSettings::ON {
audio.play(sounds.gameover.clone());
}
Now when we cargo run
we still hear audio, and if we change the default in settings.rs
to OFF
, then we won’t hear any audio.
Next we’ll create a page to expose this game setting to the player.