Bevy Version: | 0.9 | (outdated!) |
---|
Grabbing the Mouse
Click here for the full example code.
Relevant official examples:
mouse_grab
.
You can lock/release the mouse cursor using bevy's window settings API.
Here is an example that locks and hides the cursor in the primary window
on mouse click and releases it when pressing
Esc
:
use bevy::window::CursorGrabMode;
fn cursor_grab_system(
mut windows: ResMut<Windows>,
btn: Res<Input<MouseButton>>,
key: Res<Input<KeyCode>>,
) {
let window = windows.get_primary_mut().unwrap();
if btn.just_pressed(MouseButton::Left) {
// if you want to use the cursor, but not let it leave the window,
// use `Confined` mode:
window.set_cursor_grab_mode(CursorGrabMode::Confined);
// for a game that doesn't use the cursor (like a shooter):
// use `Locked` mode to keep the cursor in one place
window.set_cursor_grab_mode(CursorGrabMode::Locked);
// also hide the cursor
window.set_cursor_visibility(false);
}
if key.just_pressed(KeyCode::Escape) {
window.set_cursor_grab_mode(CursorGrabMode::None);
window.set_cursor_visibility(true);
}
}