| 1 |
|
| 2 |
|
| 3 |
use bevy::prelude::*; |
| 4 |
|
| 5 |
#[derive(Resource, Deref)] |
| 6 |
struct SoundEffect { |
| 7 |
handle: Handle<AudioSource>, |
| 8 |
} |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
impl FromWorld for SoundEffect { |
| 13 |
fn from_world(world: &mut World) -> Self { |
| 14 |
let asset_server = world.resource::<AssetServer>(); |
| 15 |
SoundEffect { |
| 16 |
handle: asset_server.load("sounds/breakout_collision.ogg"), |
| 17 |
} |
| 18 |
} |
| 19 |
} |
| 20 |
|
| 21 |
fn main() { |
| 22 |
App::new() |
| 23 |
.add_plugins(DefaultPlugins) |
| 24 |
.init_resource::<SoundEffect>() |
| 25 |
.add_systems(Startup, setup) |
| 26 |
.add_systems(Update, keyboard_event) |
| 27 |
.run(); |
| 28 |
} |
| 29 |
|
| 30 |
fn setup(mut commands: Commands) { |
| 31 |
commands.spawn(Camera2d); |
| 32 |
|
| 33 |
commands.spawn(( |
| 34 |
Text::new("Press Space to play the sound effect."), |
| 35 |
Node { |
| 36 |
position_type: PositionType::Absolute, |
| 37 |
bottom: px(12), |
| 38 |
left: px(12), |
| 39 |
..default() |
| 40 |
}, |
| 41 |
)); |
| 42 |
} |
| 43 |
|
| 44 |
|
| 45 |
fn keyboard_event( |
| 46 |
keyboard_input: Res<ButtonInput<KeyCode>>, |
| 47 |
sound_effect: Res<SoundEffect>, |
| 48 |
mut commands: Commands, |
| 49 |
) { |
| 50 |
if keyboard_input.just_pressed(KeyCode::Space) { |
| 51 |
commands.spawn(( |
| 52 |
AudioPlayer::new(sound_effect.clone()), |
| 53 |
PlaybackSettings::DESPAWN, |
| 54 |
)); |
| 55 |
} |
| 56 |
} |