use bevy::input::keyboard::KeyboardInput; use crate::prelude::*; pub struct EditorPlugin; impl Plugin for EditorPlugin { fn build(&self, app: &mut App) { app.add_systems(Startup, init_editor) .insert_resource( GizmoConfig { depth_bias: -0.1, ..default() }, ) .add_systems(Update, ( toggle_editor.run_if(on_event::()), aabb_gizmo, )) // Systems that run in the editor mode .add_systems(Update, ( selected_gizmo.run_if(any_with_component::()), selected_position.run_if(any_with_component::()), ).run_if(resource_exists::())); } } #[derive(Debug, Resource)] struct EditorActive; fn init_editor( mut commands: Commands, ) { info!("Starting editor"); } fn toggle_editor( mut events: EventReader, active: Option>, mut commands: Commands, ) { events .read() .filter(|KeyboardInput { state, key_code, .. }| *state == ButtonState::Pressed && *key_code == Some(KeyCode::F3)) .for_each(|_| match active { Some(_) => commands.remove_resource::(), None => commands.insert_resource(EditorActive), }); } fn aabb_gizmo( added: Query>, mut removed: RemovedComponents, selected: Query>, active: Option>, mut commands: Commands, ) { added.iter().for_each(|e| { commands.entity(e).insert(AabbGizmo { color: Some(Color::RED) }); }); removed.read().for_each(|e| { commands.entity(e).remove::(); }); match active { Some(_) => selected.iter().for_each(|e| { commands.entity(e).insert(AabbGizmo { color: Some(Color::RED) }); }), None => selected.iter().for_each(|e| { commands.entity(e).remove::(); }), } } /// Draw a gizmo showing cardinal directions for a selected object fn selected_gizmo( selected: Query<(Entity, &Transform, &GlobalTransform), With>, mut gizmos: Gizmos, ) { selected.iter().for_each(|(e, t, g)| { let s = g.translation(); gizmos.ray(s, Vec3::X, Color::RED); gizmos.ray(s, Vec3::Y, Color::GREEN); gizmos.ray(s, Vec3::Z, Color::BLUE); }); } fn selected_position( selected: Query<(Entity, &GlobalTransform), With>, mut debug_info: ResMut, ) { let val = selected.iter().map(|(e, gt)| { format!("\n{:?} {:?}", e, gt.translation()) }).collect::>().join(""); debug_info.set("Position".into(), val); }