Repository navigation
Description
extern crate winit;
use winit::{Event, ElementState};
fn main() {
let window = winit::WindowBuilder::new().build().unwrap();
window.set_title("winit - Cursor grabbing test");
let mut grabbed = false;
for event in window.wait_events() {
match event {
Event::KeyboardInput(ElementState::Pressed, _, _) => {
if grabbed {
grabbed = false;
window.set_cursor(winit::MouseCursor::Default);
window.set_cursor_state(winit::CursorState::Normal)
.ok().expect("could not ungrab mouse cursor");
} else {
grabbed = true;
window.set_cursor(winit::MouseCursor::NoneCursor);
window.set_cursor_state(winit::CursorState::Grab)
.ok().expect("could not grab mouse cursor");
}
},
Event::Closed => break,
a @ Event::MouseMoved(_, _) => {
println!("{:?}", a);
},
_ => (),
}
}
}
This will confine the mouse cursor within the window border. I am on Ubuntu 16.10 with X11.
Grab
[−]
Grabs the mouse cursor. The cursor's motion will be confined to this window and the window has exclusive access to further events regarding the cursor.
This is useful for first-person cameras for example.
I don't get position values that would lie outside of the window, is that expected?
Why would I want that? For a first person camera for example. You only care about the MouseDelta, so that you can rotate the camera accordingly. But if the mouse is at position (0, 0) and you move the mouse even further to the left, then it would still be at (0, 0) .
A hack would be to always reset the mouse cursor to the center of the screen after every update. The problem with this approach is that if the user moves the mouse really fast the values might get clamped.
Glfw allows this with
GLFW_CURSOR_DISABLED hides and grabs the cursor, providing virtual and unlimited cursor movement. This is useful for implementing for example 3D camera controls.
And SDL2 with https://wiki.libsdl.org/SDL_SetRelativeMouseMode Also SDL2 uses raw input ( bypasses the OS mouse speed).
Activity
[-]`CursorState::Grab` doesn't get cursor positions that lie outside of the window.[/-][+]`CursorState::Grab` doesn't receive cursor positions that lie outside of the window.[/+]Ralith commentedon May 10, 2017
Thanks to #164, this is now a non-issue on X11 if you use DeviceEvents, which report data before it's transformed/clamped/filtered into window coordinates. Other backends still need to be updated with support for their respective types of raw input.
MaikKlein commentedon May 30, 2017
@Ralith Works great!
Any reason why this hasn't been published to crates.io yet?
Ralith commentedon May 30, 2017
I can't speak for @tomaka, but I'm no longer certain that
DeviceEventis the ideal solution to this problem, per #193.Osspial commentedon Apr 24, 2019
Closing, since
DeviceEventexists and the discussion in #193 has wrapped up.Merge pull request rust-windowing#133 from jdm/pf3-magicleap