Previously, we introduced how to use KeyboardInput and CursorMoved to monitor the keyboard and the mouse. In fact, KeyboardInput and CursorMoved are Events. We can not only receive Events but also send Events, where the latter can be done by EventWriter.
In the following example, we show how to exit the app by pressing the key space
.
Exiting the app is done by sending an Event of AppExit.
fn handle_keys(keyboard_input: Res<Input<KeyCode>>, mut events: EventWriter<AppExit>) {
if keyboard_input.just_pressed(KeyCode::Space) {
events.send(AppExit);
}
}
In the system handle_keys
, we consider a parameter EventWriter<AppExit>.
We use the method send (with AppExit) of EventWriter<AppExit> to trigger an AppExit event.
The App will exit when it receives an AppExit event.
The full code is as follows:
use bevy::{
app::{App, AppExit, Update},
ecs::{event::EventWriter, system::Res},
input::{keyboard::KeyCode, Input},
DefaultPlugins,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Update, handle_keys)
.run();
}
fn handle_keys(keyboard_input: Res<Input<KeyCode>>, mut events: EventWriter<AppExit>) {
if keyboard_input.just_pressed(KeyCode::Space) {
events.send(AppExit);
}
}
By running the program, we can see that there is a window at the beginning.
The window is closed when we press the key space
.
And also the app exits when the window is closed.
➡️ Next: Custom Events
📘 Back: Table of contents