Confine the cursor to a window
Bevy version: 0.19Last updated:
Set the CursorOptions through the primary_cursor_options of the WindowPlugin:
use bevy::{
prelude::*,
window::{
CursorGrabMode,
CursorOptions,
},
};
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_cursor_options: Some(CursorOptions {
grab_mode: CursorGrabMode::Confined,
..default()
}),
..default()
}))
.run();
}
This currently has poor cross-platform support and won't work on macOS.
The cursor grab mode can also be easily overwritten from a system if you need something more dynamic:
#[allow(unused)]
fn grab_mouse(
mut cursor_options: Single<&mut CursorOptions, With<Window>>,
mouse: Res<ButtonInput<MouseButton>>,
key: Res<ButtonInput<KeyCode>>,
) {
if mouse.just_pressed(MouseButton::Left) {
cursor_options.visible = false;
cursor_options.grab_mode = CursorGrabMode::Locked;
}
if key.just_pressed(KeyCode::Escape) {
cursor_options.visible = true;
cursor_options.grab_mode = CursorGrabMode::None;
}
}