Very simple 2d/3d toggle button
It's buggy as hell, but it works. Improvements come with icing.bevy0.12
parent
087b427506
commit
a58151ee52
Binary file not shown.
Binary file not shown.
@ -0,0 +1,88 @@
|
||||
use crate::prelude::*;
|
||||
|
||||
pub(crate) struct UiPlugin;
|
||||
|
||||
impl Plugin for UiPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(Startup, initialize);
|
||||
app.add_systems(OnExit(GameState::Loading), sync_display_mode);
|
||||
app.add_systems(
|
||||
Update,
|
||||
(
|
||||
toggle_display_mode.run_if(any_component_changed::<Interaction>),
|
||||
sync_display_mode.run_if(state_changed::<DisplayState>()),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Component)]
|
||||
struct UiRoot;
|
||||
|
||||
fn initialize(mut commands: Commands) {
|
||||
commands
|
||||
.spawn((
|
||||
NodeBundle {
|
||||
style: Style {
|
||||
padding: UiRect::all(Val::Px(10.0)),
|
||||
position_type: PositionType::Absolute,
|
||||
right: Val::Px(5.0),
|
||||
bottom: Val::Px(5.0),
|
||||
..default()
|
||||
},
|
||||
background_color: Color::WHITE.with_a(0.5).into(),
|
||||
..default()
|
||||
},
|
||||
UiRoot,
|
||||
))
|
||||
.with_children(|parent| {
|
||||
parent.spawn((
|
||||
ButtonBundle {
|
||||
style: Style {
|
||||
padding: UiRect::all(Val::Px(10.0)),
|
||||
..default()
|
||||
},
|
||||
visibility: Visibility::Visible,
|
||||
..default()
|
||||
},
|
||||
DisplayState::Display2d,
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
/// When button is clicked, switch display state to that state and hide the other option.
|
||||
/// Display2d -> Click -> Display2d mode & Display3d butto
|
||||
fn toggle_display_mode(
|
||||
events: Query<(&Interaction, &DisplayState), (Changed<Interaction>, With<Button>)>,
|
||||
mut next_state: ResMut<NextState<DisplayState>>,
|
||||
) {
|
||||
events
|
||||
.iter()
|
||||
.for_each(|(interaction, display_state)| match interaction {
|
||||
Interaction::Pressed => match display_state {
|
||||
DisplayState::Display2d => next_state.set(DisplayState::Display2d),
|
||||
DisplayState::Display3d => next_state.set(DisplayState::Display3d),
|
||||
},
|
||||
_ => (),
|
||||
});
|
||||
}
|
||||
|
||||
/// Syncs the display button with the UI
|
||||
/// Runs every time the DisplayState changes
|
||||
fn sync_display_mode(
|
||||
mut query: Query<(&mut UiImage, &mut DisplayState), With<Button>>,
|
||||
state: Res<State<DisplayState>>,
|
||||
server: Res<AssetServer>,
|
||||
) {
|
||||
query.iter_mut().for_each(|(mut image, mut display_state)| {
|
||||
let (texture, target_state) = match state.get() {
|
||||
DisplayState::Display2d => (server.load("images/3d-icon.png"), DisplayState::Display3d),
|
||||
DisplayState::Display3d => (server.load("images/2d-icon.png"), DisplayState::Display2d),
|
||||
};
|
||||
*image = UiImage {
|
||||
texture,
|
||||
..default()
|
||||
};
|
||||
*display_state = target_state;
|
||||
});
|
||||
}
|
||||
Loading…
Reference in New Issue