bevy/examples/ui/button.rs

95 lines
3 KiB
Rust
Raw Normal View History

use bevy::prelude::*;
2020-07-28 20:43:07 +00:00
/// This example illustrates how to create a button that changes color and text based on its interaction state.
fn main() {
App::build()
.add_plugins(DefaultPlugins)
2020-07-18 21:36:31 +00:00
.init_resource::<ButtonMaterials>()
.add_startup_system(setup.system())
.add_system(button_system.system())
.run();
}
2020-07-18 21:36:31 +00:00
struct ButtonMaterials {
normal: Handle<ColorMaterial>,
hovered: Handle<ColorMaterial>,
pressed: Handle<ColorMaterial>,
}
impl FromResources for ButtonMaterials {
fn from_resources(resources: &Resources) -> Self {
let mut materials = resources.get_mut::<Assets<ColorMaterial>>().unwrap();
ButtonMaterials {
2020-10-12 23:54:22 +00:00
normal: materials.add(Color::rgb(0.15, 0.15, 0.15).into()),
hovered: materials.add(Color::rgb(0.25, 0.25, 0.25).into()),
pressed: materials.add(Color::rgb(0.35, 0.75, 0.35).into()),
2020-07-18 21:36:31 +00:00
}
}
}
fn button_system(
2020-07-18 21:36:31 +00:00
button_materials: Res<ButtonMaterials>,
mut interaction_query: Query<(
2020-07-18 21:36:31 +00:00
&Button,
Mutated<Interaction>,
2020-07-18 21:36:31 +00:00
&mut Handle<ColorMaterial>,
&Children,
)>,
mut text_query: Query<&mut Text>,
) {
for (_button, interaction, mut material, children) in interaction_query.iter_mut() {
let mut text = text_query.get_mut(children[0]).unwrap();
match *interaction {
Interaction::Clicked => {
text.value = "Press".to_string();
*material = button_materials.pressed.clone();
}
Interaction::Hovered => {
text.value = "Hover".to_string();
*material = button_materials.hovered.clone();
}
Interaction::None => {
text.value = "Button".to_string();
*material = button_materials.normal.clone();
}
}
}
}
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
2020-07-18 21:36:31 +00:00
button_materials: Res<ButtonMaterials>,
) {
commands
// ui camera
2020-07-25 06:04:45 +00:00
.spawn(UiCameraComponents::default())
.spawn(ButtonComponents {
2020-07-26 19:27:09 +00:00
style: Style {
size: Size::new(Val::Px(150.0), Val::Px(65.0)),
// center button
margin: Rect::all(Val::Auto),
// horizontally center child text
justify_content: JustifyContent::Center,
// vertically center child text
align_items: AlignItems::Center,
2020-07-25 06:04:45 +00:00
..Default::default()
},
material: button_materials.normal.clone(),
..Default::default()
})
.with_children(|parent| {
parent.spawn(TextComponents {
text: Text {
value: "Button".to_string(),
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
style: TextStyle {
font_size: 40.0,
2020-10-12 23:54:22 +00:00
color: Color::rgb(0.9, 0.9, 0.9),
},
},
..Default::default()
});
});
}