Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/games/game_menu.rs
9550 views
1
//! This example will display a simple menu using Bevy UI where you can start a new game,
2
//! change some settings or quit. There is no actual game, it will just display the current
3
//! settings for 5 seconds before going back to the menu.
4
5
use bevy::prelude::*;
6
7
const TEXT_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);
8
9
// Enum that will be used as a global state for the game
10
#[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)]
11
enum GameState {
12
#[default]
13
Splash,
14
Menu,
15
Game,
16
}
17
18
// One of the two settings that can be set through the menu. It will be a resource in the app
19
#[derive(Resource, Debug, PartialEq, Eq, Clone, Copy)]
20
enum DisplayQuality {
21
Low,
22
Medium,
23
High,
24
}
25
26
#[derive(Component)]
27
struct Setting<T>(T);
28
29
// One of the two settings that can be set through the menu. It will be a resource in the app
30
#[derive(Resource, Debug, PartialEq, Eq, Clone, Copy)]
31
struct Volume(u32);
32
33
fn main() {
34
App::new()
35
.add_plugins(DefaultPlugins)
36
// Insert as resource the initial value for the settings resources
37
.insert_resource(DisplayQuality::Medium)
38
.insert_resource(Volume(7))
39
// Declare the game state, whose starting value is determined by the `Default` trait
40
.init_state::<GameState>()
41
.add_systems(Startup, setup)
42
// Adds the plugins for each state
43
.add_plugins((splash::splash_plugin, menu::menu_plugin, game::game_plugin))
44
.run();
45
}
46
47
fn setup(mut commands: Commands) {
48
commands.spawn(Camera2d);
49
}
50
51
mod splash {
52
use bevy::prelude::*;
53
54
use super::GameState;
55
56
// This plugin will display a splash screen with Bevy logo for 1 second before switching to the menu
57
pub fn splash_plugin(app: &mut App) {
58
// As this plugin is managing the splash screen, it will focus on the state `GameState::Splash`
59
app
60
// When entering the state, spawn everything needed for this screen
61
.add_systems(OnEnter(GameState::Splash), splash_setup)
62
// While in this state, run the `countdown` system
63
.add_systems(Update, countdown.run_if(in_state(GameState::Splash)));
64
}
65
66
// Tag component used to tag entities added on the splash screen
67
#[derive(Component)]
68
struct OnSplashScreen;
69
70
// Newtype to use a `Timer` for this screen as a resource
71
#[derive(Resource, Deref, DerefMut)]
72
struct SplashTimer(Timer);
73
74
fn splash_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
75
let icon = asset_server.load("branding/icon.png");
76
// Display the logo
77
commands.spawn((
78
// This entity will be despawned when exiting the state
79
DespawnOnExit(GameState::Splash),
80
Node {
81
align_items: AlignItems::Center,
82
justify_content: JustifyContent::Center,
83
width: percent(100),
84
height: percent(100),
85
..default()
86
},
87
OnSplashScreen,
88
children![(
89
ImageNode::new(icon),
90
Node {
91
// This will set the logo to be 200px wide, and auto adjust its height
92
width: px(200),
93
..default()
94
},
95
)],
96
));
97
// Insert the timer as a resource
98
commands.insert_resource(SplashTimer(Timer::from_seconds(1.0, TimerMode::Once)));
99
}
100
101
// Tick the timer, and change state when finished
102
fn countdown(
103
mut game_state: ResMut<NextState<GameState>>,
104
time: Res<Time>,
105
mut timer: ResMut<SplashTimer>,
106
) {
107
if timer.tick(time.delta()).is_finished() {
108
game_state.set(GameState::Menu);
109
}
110
}
111
}
112
113
mod game {
114
use bevy::{
115
color::palettes::basic::{BLUE, LIME},
116
prelude::*,
117
};
118
119
use super::{DisplayQuality, GameState, Volume, TEXT_COLOR};
120
121
// This plugin will contain the game. In this case, it's just be a screen that will
122
// display the current settings for 5 seconds before returning to the menu
123
pub fn game_plugin(app: &mut App) {
124
app.add_systems(OnEnter(GameState::Game), game_setup)
125
.add_systems(Update, game.run_if(in_state(GameState::Game)));
126
}
127
128
// Tag component used to tag entities added on the game screen
129
#[derive(Component)]
130
struct OnGameScreen;
131
132
#[derive(Resource, Deref, DerefMut)]
133
struct GameTimer(Timer);
134
135
fn game_setup(
136
mut commands: Commands,
137
display_quality: Res<DisplayQuality>,
138
volume: Res<Volume>,
139
) {
140
commands.spawn((
141
DespawnOnExit(GameState::Game),
142
Node {
143
width: percent(100),
144
height: percent(100),
145
// center children
146
align_items: AlignItems::Center,
147
justify_content: JustifyContent::Center,
148
..default()
149
},
150
OnGameScreen,
151
children![(
152
Node {
153
// This will display its children in a column, from top to bottom
154
flex_direction: FlexDirection::Column,
155
// `align_items` will align children on the cross axis. Here the main axis is
156
// vertical (column), so the cross axis is horizontal. This will center the
157
// children
158
align_items: AlignItems::Center,
159
..default()
160
},
161
BackgroundColor(Color::BLACK),
162
children![
163
(
164
Text::new("Will be back to the menu shortly..."),
165
TextFont {
166
font_size: FontSize::Px(67.0),
167
..default()
168
},
169
TextColor(TEXT_COLOR),
170
Node {
171
margin: UiRect::all(px(50)),
172
..default()
173
},
174
),
175
(
176
Text::default(),
177
Node {
178
margin: UiRect::all(px(50)),
179
..default()
180
},
181
children![
182
(
183
TextSpan(format!("quality: {:?}", *display_quality)),
184
TextFont {
185
font_size: FontSize::Px(50.0),
186
..default()
187
},
188
TextColor(BLUE.into()),
189
),
190
(
191
TextSpan::new(" - "),
192
TextFont {
193
font_size: FontSize::Px(50.0),
194
..default()
195
},
196
TextColor(TEXT_COLOR),
197
),
198
(
199
TextSpan(format!("volume: {:?}", *volume)),
200
TextFont {
201
font_size: FontSize::Px(50.0),
202
..default()
203
},
204
TextColor(LIME.into()),
205
),
206
]
207
),
208
]
209
)],
210
));
211
// Spawn a 5 seconds timer to trigger going back to the menu
212
commands.insert_resource(GameTimer(Timer::from_seconds(5.0, TimerMode::Once)));
213
}
214
215
// Tick the timer, and change state when finished
216
fn game(
217
time: Res<Time>,
218
mut game_state: ResMut<NextState<GameState>>,
219
mut timer: ResMut<GameTimer>,
220
) {
221
if timer.tick(time.delta()).is_finished() {
222
game_state.set(GameState::Menu);
223
}
224
}
225
}
226
227
mod menu {
228
use bevy::{
229
app::AppExit,
230
color::palettes::css::CRIMSON,
231
ecs::spawn::{SpawnIter, SpawnWith},
232
prelude::*,
233
};
234
235
use super::{DisplayQuality, GameState, Setting, Volume, TEXT_COLOR};
236
237
// This plugin manages the menu, with 5 different screens:
238
// - a main menu with "New Game", "Settings", "Quit"
239
// - a settings menu with two submenus and a back button
240
// - two settings screen with a setting that can be set and a back button
241
pub fn menu_plugin(app: &mut App) {
242
app
243
// At start, the menu is not enabled. This will be changed in `menu_setup` when
244
// entering the `GameState::Menu` state.
245
// Current screen in the menu is handled by an independent state from `GameState`
246
.init_state::<MenuState>()
247
.add_systems(OnEnter(GameState::Menu), menu_setup)
248
// Systems to handle the main menu screen
249
.add_systems(OnEnter(MenuState::Main), main_menu_setup)
250
// Systems to handle the settings menu screen
251
.add_systems(OnEnter(MenuState::Settings), settings_menu_setup)
252
// Systems to handle the display settings screen
253
.add_systems(
254
OnEnter(MenuState::SettingsDisplay),
255
display_settings_menu_setup,
256
)
257
.add_systems(
258
Update,
259
(setting_button::<DisplayQuality>.run_if(in_state(MenuState::SettingsDisplay)),),
260
)
261
// Systems to handle the sound settings screen
262
.add_systems(OnEnter(MenuState::SettingsSound), sound_settings_menu_setup)
263
.add_systems(
264
Update,
265
setting_button::<Volume>.run_if(in_state(MenuState::SettingsSound)),
266
)
267
// Common systems to all screens that handles buttons behavior
268
.add_systems(
269
Update,
270
(menu_action, button_system).run_if(in_state(GameState::Menu)),
271
);
272
}
273
274
// State used for the current menu screen
275
#[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)]
276
enum MenuState {
277
Main,
278
Settings,
279
SettingsDisplay,
280
SettingsSound,
281
#[default]
282
Disabled,
283
}
284
285
// Tag component used to tag entities added on the main menu screen
286
#[derive(Component)]
287
struct OnMainMenuScreen;
288
289
// Tag component used to tag entities added on the settings menu screen
290
#[derive(Component)]
291
struct OnSettingsMenuScreen;
292
293
// Tag component used to tag entities added on the display settings menu screen
294
#[derive(Component)]
295
struct OnDisplaySettingsMenuScreen;
296
297
// Tag component used to tag entities added on the sound settings menu screen
298
#[derive(Component)]
299
struct OnSoundSettingsMenuScreen;
300
301
const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
302
const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
303
const HOVERED_PRESSED_BUTTON: Color = Color::srgb(0.25, 0.65, 0.25);
304
const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
305
306
// Tag component used to mark which setting is currently selected
307
#[derive(Component)]
308
struct SelectedOption;
309
310
// All actions that can be triggered from a button click
311
#[derive(Component)]
312
enum MenuButtonAction {
313
Play,
314
Settings,
315
SettingsDisplay,
316
SettingsSound,
317
BackToMainMenu,
318
BackToSettings,
319
Quit,
320
}
321
322
// This system handles changing all buttons color based on mouse interaction
323
fn button_system(
324
mut interaction_query: Query<
325
(&Interaction, &mut BackgroundColor, Option<&SelectedOption>),
326
(Changed<Interaction>, With<Button>),
327
>,
328
) {
329
for (interaction, mut background_color, selected) in &mut interaction_query {
330
*background_color = match (*interaction, selected) {
331
(Interaction::Pressed, _) | (Interaction::None, Some(_)) => PRESSED_BUTTON.into(),
332
(Interaction::Hovered, Some(_)) => HOVERED_PRESSED_BUTTON.into(),
333
(Interaction::Hovered, None) => HOVERED_BUTTON.into(),
334
(Interaction::None, None) => NORMAL_BUTTON.into(),
335
}
336
}
337
}
338
339
// This system updates the settings when a new value for a setting is selected, and marks
340
// the button as the one currently selected
341
fn setting_button<T: Resource + Component + PartialEq + Copy>(
342
interaction_query: Query<
343
(&Interaction, &Setting<T>, Entity),
344
(Changed<Interaction>, With<Button>),
345
>,
346
selected_query: Single<(Entity, &mut BackgroundColor), With<SelectedOption>>,
347
mut commands: Commands,
348
mut setting: ResMut<T>,
349
) {
350
let (previous_button, mut previous_button_color) = selected_query.into_inner();
351
for (interaction, button_setting, entity) in &interaction_query {
352
if *interaction == Interaction::Pressed && *setting != button_setting.0 {
353
*previous_button_color = NORMAL_BUTTON.into();
354
commands.entity(previous_button).remove::<SelectedOption>();
355
commands.entity(entity).insert(SelectedOption);
356
*setting = button_setting.0;
357
}
358
}
359
}
360
361
fn menu_setup(mut menu_state: ResMut<NextState<MenuState>>) {
362
menu_state.set(MenuState::Main);
363
}
364
365
fn main_menu_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
366
// Common style for all buttons on the screen
367
let button_node = Node {
368
width: px(300),
369
height: px(65),
370
margin: UiRect::all(px(20)),
371
justify_content: JustifyContent::Center,
372
align_items: AlignItems::Center,
373
..default()
374
};
375
let button_icon_node = Node {
376
width: px(30),
377
// This takes the icons out of the flexbox flow, to be positioned exactly
378
position_type: PositionType::Absolute,
379
// The icon will be close to the left border of the button
380
left: px(10),
381
..default()
382
};
383
let button_text_font = TextFont {
384
font_size: FontSize::Px(33.0),
385
..default()
386
};
387
388
let right_icon = asset_server.load("textures/Game Icons/right.png");
389
let wrench_icon = asset_server.load("textures/Game Icons/wrench.png");
390
let exit_icon = asset_server.load("textures/Game Icons/exitRight.png");
391
392
commands.spawn((
393
DespawnOnExit(MenuState::Main),
394
Node {
395
width: percent(100),
396
height: percent(100),
397
align_items: AlignItems::Center,
398
justify_content: JustifyContent::Center,
399
..default()
400
},
401
OnMainMenuScreen,
402
children![(
403
Node {
404
flex_direction: FlexDirection::Column,
405
align_items: AlignItems::Center,
406
..default()
407
},
408
BackgroundColor(CRIMSON.into()),
409
children![
410
// Display the game name
411
(
412
Text::new("Bevy Game Menu UI"),
413
TextFont {
414
font_size: FontSize::Px(67.0),
415
..default()
416
},
417
TextColor(TEXT_COLOR),
418
Node {
419
margin: UiRect::all(px(50)),
420
..default()
421
},
422
),
423
// Display three buttons for each action available from the main menu:
424
// - new game
425
// - settings
426
// - quit
427
(
428
Button,
429
button_node.clone(),
430
BackgroundColor(NORMAL_BUTTON),
431
MenuButtonAction::Play,
432
children![
433
(ImageNode::new(right_icon), button_icon_node.clone()),
434
(
435
Text::new("New Game"),
436
button_text_font.clone(),
437
TextColor(TEXT_COLOR),
438
),
439
]
440
),
441
(
442
Button,
443
button_node.clone(),
444
BackgroundColor(NORMAL_BUTTON),
445
MenuButtonAction::Settings,
446
children![
447
(ImageNode::new(wrench_icon), button_icon_node.clone()),
448
(
449
Text::new("Settings"),
450
button_text_font.clone(),
451
TextColor(TEXT_COLOR),
452
),
453
]
454
),
455
(
456
Button,
457
button_node,
458
BackgroundColor(NORMAL_BUTTON),
459
MenuButtonAction::Quit,
460
children![
461
(ImageNode::new(exit_icon), button_icon_node),
462
(Text::new("Quit"), button_text_font, TextColor(TEXT_COLOR),),
463
]
464
),
465
]
466
)],
467
));
468
}
469
470
fn settings_menu_setup(mut commands: Commands) {
471
let button_node = Node {
472
width: px(200),
473
height: px(65),
474
margin: UiRect::all(px(20)),
475
justify_content: JustifyContent::Center,
476
align_items: AlignItems::Center,
477
..default()
478
};
479
480
let button_text_style = (
481
TextFont {
482
font_size: FontSize::Px(33.0),
483
..default()
484
},
485
TextColor(TEXT_COLOR),
486
);
487
488
commands.spawn((
489
DespawnOnExit(MenuState::Settings),
490
Node {
491
width: percent(100),
492
height: percent(100),
493
align_items: AlignItems::Center,
494
justify_content: JustifyContent::Center,
495
..default()
496
},
497
OnSettingsMenuScreen,
498
children![(
499
Node {
500
flex_direction: FlexDirection::Column,
501
align_items: AlignItems::Center,
502
..default()
503
},
504
BackgroundColor(CRIMSON.into()),
505
Children::spawn(SpawnIter(
506
[
507
(MenuButtonAction::SettingsDisplay, "Display"),
508
(MenuButtonAction::SettingsSound, "Sound"),
509
(MenuButtonAction::BackToMainMenu, "Back"),
510
]
511
.into_iter()
512
.map(move |(action, text)| {
513
(
514
Button,
515
button_node.clone(),
516
BackgroundColor(NORMAL_BUTTON),
517
action,
518
children![(Text::new(text), button_text_style.clone())],
519
)
520
})
521
))
522
)],
523
));
524
}
525
526
fn display_settings_menu_setup(mut commands: Commands, display_quality: Res<DisplayQuality>) {
527
fn button_node() -> Node {
528
Node {
529
width: px(200),
530
height: px(65),
531
margin: UiRect::all(px(20)),
532
justify_content: JustifyContent::Center,
533
align_items: AlignItems::Center,
534
..default()
535
}
536
}
537
fn button_text_style() -> impl Bundle {
538
(
539
TextFont {
540
font_size: FontSize::Px(33.0),
541
..default()
542
},
543
TextColor(TEXT_COLOR),
544
)
545
}
546
547
let display_quality = *display_quality;
548
commands.spawn((
549
DespawnOnExit(MenuState::SettingsDisplay),
550
Node {
551
width: percent(100),
552
height: percent(100),
553
align_items: AlignItems::Center,
554
justify_content: JustifyContent::Center,
555
..default()
556
},
557
OnDisplaySettingsMenuScreen,
558
children![(
559
Node {
560
flex_direction: FlexDirection::Column,
561
align_items: AlignItems::Center,
562
..default()
563
},
564
BackgroundColor(CRIMSON.into()),
565
children![
566
// Create a new `Node`, this time not setting its `flex_direction`. It will
567
// use the default value, `FlexDirection::Row`, from left to right.
568
(
569
Node {
570
align_items: AlignItems::Center,
571
..default()
572
},
573
BackgroundColor(CRIMSON.into()),
574
Children::spawn((
575
// Display a label for the current setting
576
Spawn((Text::new("Display Quality"), button_text_style())),
577
SpawnWith(move |parent: &mut ChildSpawner| {
578
for quality_setting in [
579
DisplayQuality::Low,
580
DisplayQuality::Medium,
581
DisplayQuality::High,
582
] {
583
let mut entity = parent.spawn((
584
Button,
585
Node {
586
width: px(150),
587
height: px(65),
588
..button_node()
589
},
590
BackgroundColor(NORMAL_BUTTON),
591
Setting(quality_setting),
592
children![(
593
Text::new(format!("{quality_setting:?}")),
594
button_text_style(),
595
)],
596
));
597
if display_quality == quality_setting {
598
entity.insert(SelectedOption);
599
}
600
}
601
})
602
))
603
),
604
// Display the back button to return to the settings screen
605
(
606
Button,
607
button_node(),
608
BackgroundColor(NORMAL_BUTTON),
609
MenuButtonAction::BackToSettings,
610
children![(Text::new("Back"), button_text_style())]
611
)
612
]
613
)],
614
));
615
}
616
617
fn sound_settings_menu_setup(mut commands: Commands, volume: Res<Volume>) {
618
let button_node = Node {
619
width: px(200),
620
height: px(65),
621
margin: UiRect::all(px(20)),
622
justify_content: JustifyContent::Center,
623
align_items: AlignItems::Center,
624
..default()
625
};
626
let button_text_style = (
627
TextFont {
628
font_size: FontSize::Px(33.0),
629
..default()
630
},
631
TextColor(TEXT_COLOR),
632
);
633
634
let volume = *volume;
635
let button_node_clone = button_node.clone();
636
commands.spawn((
637
DespawnOnExit(MenuState::SettingsSound),
638
Node {
639
width: percent(100),
640
height: percent(100),
641
align_items: AlignItems::Center,
642
justify_content: JustifyContent::Center,
643
..default()
644
},
645
OnSoundSettingsMenuScreen,
646
children![(
647
Node {
648
flex_direction: FlexDirection::Column,
649
align_items: AlignItems::Center,
650
..default()
651
},
652
BackgroundColor(CRIMSON.into()),
653
children![
654
(
655
Node {
656
align_items: AlignItems::Center,
657
..default()
658
},
659
BackgroundColor(CRIMSON.into()),
660
Children::spawn((
661
Spawn((Text::new("Volume"), button_text_style.clone())),
662
SpawnWith(move |parent: &mut ChildSpawner| {
663
for volume_setting in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] {
664
let mut entity = parent.spawn((
665
Button,
666
Node {
667
width: px(30),
668
height: px(65),
669
..button_node_clone.clone()
670
},
671
BackgroundColor(NORMAL_BUTTON),
672
Setting(Volume(volume_setting)),
673
));
674
if volume == Volume(volume_setting) {
675
entity.insert(SelectedOption);
676
}
677
}
678
})
679
))
680
),
681
(
682
Button,
683
button_node,
684
BackgroundColor(NORMAL_BUTTON),
685
MenuButtonAction::BackToSettings,
686
children![(Text::new("Back"), button_text_style)]
687
)
688
]
689
)],
690
));
691
}
692
693
fn menu_action(
694
interaction_query: Query<
695
(&Interaction, &MenuButtonAction),
696
(Changed<Interaction>, With<Button>),
697
>,
698
mut app_exit_writer: MessageWriter<AppExit>,
699
mut menu_state: ResMut<NextState<MenuState>>,
700
mut game_state: ResMut<NextState<GameState>>,
701
) {
702
for (interaction, menu_button_action) in &interaction_query {
703
if *interaction == Interaction::Pressed {
704
match menu_button_action {
705
MenuButtonAction::Quit => {
706
app_exit_writer.write(AppExit::Success);
707
}
708
MenuButtonAction::Play => {
709
game_state.set(GameState::Game);
710
menu_state.set(MenuState::Disabled);
711
}
712
MenuButtonAction::Settings => menu_state.set(MenuState::Settings),
713
MenuButtonAction::SettingsDisplay => {
714
menu_state.set(MenuState::SettingsDisplay);
715
}
716
MenuButtonAction::SettingsSound => {
717
menu_state.set(MenuState::SettingsSound);
718
}
719
MenuButtonAction::BackToMainMenu => menu_state.set(MenuState::Main),
720
MenuButtonAction::BackToSettings => {
721
menu_state.set(MenuState::Settings);
722
}
723
}
724
}
725
}
726
}
727
}
728
729