properly deal w cursor locking

This commit is contained in:
2024-06-05 01:03:50 -04:00
parent 65ba54f2f5
commit 44a37114e3
2 changed files with 26 additions and 10 deletions

View File

@@ -1,7 +1,11 @@
use std::{f32::consts::PI, time::Duration};
use nalgebra::Rotation3;
use winit::{dpi::LogicalPosition, keyboard::KeyCode as Key, window::CursorGrabMode};
use winit::{
dpi::{LogicalPosition, PhysicalPosition},
keyboard::KeyCode as Key,
window::CursorGrabMode,
};
use super::Client;
@@ -12,25 +16,35 @@ impl Client<'_> {
if input.just_pressed(Key::Escape) {
if let Some(window) = &self.window {
self.grabbed_cursor = !self.grabbed_cursor;
let mode = if self.grabbed_cursor {
if self.grabbed_cursor {
window.set_cursor_visible(false);
CursorGrabMode::Locked
window
.set_cursor_grab(CursorGrabMode::Locked)
.map(|_| {
self.keep_cursor = false;
})
.or_else(|_| {
self.keep_cursor = true;
window.set_cursor_grab(CursorGrabMode::Confined)
})
.expect("wah");
} else {
self.keep_cursor = false;
window.set_cursor_visible(true);
CursorGrabMode::None
window.set_cursor_grab(CursorGrabMode::None).expect("wah");
};
#[cfg(not(target_os = "windows"))]
window.set_cursor_grab(mode).expect("wah");
}
return;
}
if self.grabbed_cursor {
if let Some(window) = &self.window {
if self.keep_cursor {
let size = window.inner_size();
window
.set_cursor_position(LogicalPosition::new(size.width / 2, size.height / 2))
.set_cursor_position(PhysicalPosition::new(size.width / 2, size.height / 2))
.expect("wah");
}
}
let delta = input.mouse_delta;
if delta.x != 0.0 {
state.camera.orientation = Rotation3::from_axis_angle(

View File

@@ -26,6 +26,7 @@ pub struct Client<'a> {
prev_frame: Instant,
prev_update: Instant,
grabbed_cursor: bool,
keep_cursor: bool,
}
impl Client<'_> {
@@ -41,6 +42,7 @@ impl Client<'_> {
prev_update: Instant::now(),
target: Instant::now(),
grabbed_cursor: false,
keep_cursor: false,
}
}