idanarye / bevy-egui-kbgp

Better keyboard and gamepad story for egui in Bevy
Apache License 2.0
20 stars 2 forks source link

If a button that triggers a KBGP action was pressed to get in to a menu state, it'll trigger said action immediartely on entry #5

Closed idanarye closed 2 years ago

idanarye commented 2 years ago
use bevy::prelude::*;
use bevy_egui::{EguiContext, EguiPlugin};
use bevy_egui_kbgp::prelude::*;
use bevy_egui_kbgp::{bevy_egui, egui};

#[derive(Hash, Debug, PartialEq, Eq, Clone, Copy)]
enum AppState {
    NoMenu,
    Menu,
}

#[derive(Clone, PartialEq, Eq)]
enum KbgpActions {
    CloseMenu,
}

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_plugin(EguiPlugin)
        .add_plugin(KbgpPlugin)
        .insert_resource(KbgpSettings {
            bindings: {
                bevy_egui_kbgp::KbgpNavBindings::default().with_key(
                    KeyCode::Escape,
                    KbgpNavCommand::user(KbgpActions::CloseMenu),
                )
            },
            ..Default::default()
        })
        .add_state(AppState::NoMenu)
        .add_system_set(SystemSet::on_update(AppState::NoMenu).with_system(listen_to_menu_key))
        .add_system_set(SystemSet::on_update(AppState::Menu).with_system(ui_system))
        .run();
}

fn listen_to_menu_key(
    mut keys: ResMut<Input<KeyCode>>,
    mut state: ResMut<State<AppState>>,
    mut egui_context: ResMut<EguiContext>,
) {
    if keys.just_pressed(KeyCode::Escape) {
        state.set(AppState::Menu).unwrap();
        keys.clear();
        egui_context.ctx_mut().kbgp_clear_input();
    }
}

fn ui_system(mut egui_context: ResMut<EguiContext>, mut state: ResMut<State<AppState>>) {
    egui::CentralPanel::default().show(egui_context.ctx_mut(), |ui| {
        ui.button("Does Nothing")
            .kbgp_navigation()
            .kbgp_initial_focus();
        if ui.kbgp_user_action() == Some(KbgpActions::CloseMenu) {
            state.set(AppState::NoMenu).unwrap();
        }
    });
}
idanarye commented 2 years ago

OK - so the issue was that ui_system was supposed to clear keys. But my fix to #3 should present a nicer fix - it makes kbgp_user_action usable even when there are no egui widges registered in KBGP - which means that listen_to_menu_key can use it as well and ui_system can just use kbgp_clear_input instead of touching Input resources.

idanarye commented 2 years ago

Of course, I should mention it in the docs.