From b66c99816bdd37f2d66c91c9c05c28a88bbb376f Mon Sep 17 00:00:00 2001 From: copygirl Date: Wed, 26 Mar 2025 11:24:46 +0100 Subject: [PATCH] Ungrab mouse when window loses focus --- src/camera_controller.rs | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/src/camera_controller.rs b/src/camera_controller.rs index 73fcb0b..6c86a7b 100644 --- a/src/camera_controller.rs +++ b/src/camera_controller.rs @@ -29,13 +29,14 @@ fn capture_mouse( key: Res>, ) { if mouse.just_pressed(MouseButton::Left) { - window.cursor_options.visible = false; - window.cursor_options.grab_mode = CursorGrabMode::Locked; + set_mouse_grabbed(&mut window, true); } - if key.just_pressed(KeyCode::Escape) { - window.cursor_options.visible = true; - window.cursor_options.grab_mode = CursorGrabMode::None; + set_mouse_grabbed(&mut window, false); + } + // Ungrab the mouse if window doesn't have focus. + if !window.focused { + set_mouse_grabbed(&mut window, false); } } @@ -45,7 +46,7 @@ fn camera_mouse_rotation( mouse_motion: Res, ) { // Mouse must be grabbed by the window for this system to run. - if window.cursor_options.grab_mode != CursorGrabMode::Locked { + if !mouse_grabbed(&window) { return; } @@ -71,7 +72,7 @@ fn camera_keyboard_translation( key: Res>, ) { // Mouse must be grabbed by the window for this system to run. - if window.cursor_options.grab_mode != CursorGrabMode::Locked { + if !mouse_grabbed(&window) { return; } @@ -108,3 +109,16 @@ fn camera_keyboard_translation( transform.translation += translation; } } + +fn mouse_grabbed(window: &Window) -> bool { + window.cursor_options.grab_mode == CursorGrabMode::Locked +} + +fn set_mouse_grabbed(window: &mut Window, value: bool) { + window.cursor_options.visible = !value; + window.cursor_options.grab_mode = if value { + CursorGrabMode::Locked + } else { + CursorGrabMode::None + }; +}