Repository navigation
Expand file tree
/
Copy patheffect_tail.rs
More file actions
82 lines (75 loc) · 2.36 KB
/
Copy patheffect_tail.rs
File metadata and controls
82 lines (75 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use bevy::prelude::*;
use bevy_kira_audio::prelude::*;
use std::time::Duration;
/// Reverb and delay keep sounding after the sound feeding them has ended. A sound with effects of
/// its own lets them ring out when it ends by itself, but cuts them off when it is stopped.
fn main() {
App::new()
.add_plugins((DefaultPlugins, AudioPlugin))
.add_systems(Startup, setup)
.add_systems(Update, controls)
.run();
}
#[derive(Resource)]
struct Sounds {
plop: Handle<AudioSource>,
music: Handle<AudioSource>,
}
#[derive(Resource, Default)]
struct Music(Option<Handle<AudioInstance>>);
fn reverb() -> ReverbBuilder {
ReverbBuilder::new().feedback(0.9).damping(0.2).mix(0.7_f32)
}
fn controls(
keys: Res<ButtonInput<KeyCode>>,
audio: Res<Audio>,
sounds: Res<Sounds>,
mut music: ResMut<Music>,
mut instances: ResMut<Assets<AudioInstance>>,
) {
if keys.just_pressed(KeyCode::KeyP) {
audio.play(sounds.plop.clone()).with_effect(reverb());
}
if keys.just_pressed(KeyCode::KeyM) && music.0.is_none() {
music.0 = Some(
audio
.play(sounds.music.clone())
.with_effect(reverb())
.looped()
.handle(),
);
}
if keys.just_pressed(KeyCode::KeyS)
&& let Some(handle) = music.0.take()
&& let Some(mut instance) = instances.get_mut(&handle)
{
instance.stop(AudioTween::linear(Duration::from_millis(500)));
}
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
commands.insert_resource(Sounds {
plop: asset_server.load("sounds/plop.ogg"),
music: asset_server.load("sounds/loop.ogg"),
});
commands.init_resource::<Music>();
commands.spawn((
Node {
padding: UiRect::all(Val::Px(40.0)),
..default()
},
children![(
Text::new(
"Effect tails\n\n\
[P] play a plop: it ends by itself and its reverb rings out\n\
[M] play music through the same reverb\n\
[S] stop the music: its reverb fades out with it",
),
TextFont {
font: asset_server.load("fonts/monogram.ttf").into(),
font_size: 26.0.into(),
..default()
},
)],
));
}