|
| 1 | +use bevy::prelude::*; |
| 2 | +use bevy_editor_core::SelectedEntity; |
| 3 | + |
| 4 | +pub struct OutlineGizmoPlugin; |
| 5 | +impl Plugin for OutlineGizmoPlugin { |
| 6 | + fn build(&self, app: &mut App) { |
| 7 | + app.init_resource::<ShowOutlines>() |
| 8 | + .add_systems(Startup, spawn_gizmo_toggle_ui) |
| 9 | + .add_systems(Update, outline_gizmo_system) |
| 10 | + .add_systems(Update, update_gizmo_toggle_text); |
| 11 | + } |
| 12 | +} |
| 13 | + |
| 14 | +#[derive(Resource, Default)] |
| 15 | +pub struct ShowOutlines(pub bool); |
| 16 | + |
| 17 | +// Marker for the toggle button text |
| 18 | +#[derive(Component)] |
| 19 | +struct GizmoToggleText; |
| 20 | + |
| 21 | +pub fn outline_gizmo_system( |
| 22 | + show: Res<ShowOutlines>, |
| 23 | + query: Query<&Transform>, |
| 24 | + selected_entity: Res<SelectedEntity>, |
| 25 | + mut gizmos: Gizmos, |
| 26 | +) { |
| 27 | + if !show.0 { |
| 28 | + return; |
| 29 | + } |
| 30 | + if let Some(entity) = selected_entity.0 { |
| 31 | + if let Ok(transform) = query.get(entity) { |
| 32 | + gizmos.cuboid(*transform, Color::srgb(1.0, 0.0, 0.0)); |
| 33 | + } |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +pub fn spawn_gizmo_toggle_ui(mut commands: Commands) { |
| 38 | + info!("Spawning Gizmo Toggle UI"); |
| 39 | + commands |
| 40 | + .spawn(( |
| 41 | + Node { |
| 42 | + position_type: PositionType::Absolute, |
| 43 | + top: Val::Px(20.0), |
| 44 | + right: Val::Px(20.0), |
| 45 | + width: Val::Px(100.0), |
| 46 | + height: Val::Px(15.0), |
| 47 | + align_items: AlignItems::Center, |
| 48 | + justify_content: JustifyContent::Center, |
| 49 | + ..default() |
| 50 | + }, |
| 51 | + BackgroundColor(Color::srgb(0.2, 0.2, 0.2)), |
| 52 | + )) |
| 53 | + .with_children(|parent| { |
| 54 | + parent.spawn(( |
| 55 | + Text::new("Show Outlines"), |
| 56 | + TextFont::from_font_size(10.0), |
| 57 | + GizmoToggleText, |
| 58 | + )); |
| 59 | + }) |
| 60 | + .observe( |
| 61 | + |_trigger: Trigger<Pointer<Click>>, mut show_outlines: ResMut<ShowOutlines>| { |
| 62 | + show_outlines.0 = !show_outlines.0; |
| 63 | + }, |
| 64 | + ); |
| 65 | +} |
| 66 | + |
| 67 | +// System to update the button text when ShowOutlines changes |
| 68 | +fn update_gizmo_toggle_text( |
| 69 | + show_outlines: Res<ShowOutlines>, |
| 70 | + mut query: Query<&mut Text, With<GizmoToggleText>>, |
| 71 | +) { |
| 72 | + if show_outlines.is_changed() { |
| 73 | + for mut text in &mut query { |
| 74 | + text.0 = if show_outlines.0 { |
| 75 | + "Hide Outlines".into() |
| 76 | + } else { |
| 77 | + "Show Outlines".into() |
| 78 | + }; |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments