Skip to content

Commit 6ce8e50

Browse files
committed
Add mouse grab example (#4114)
Fixes #4094
1 parent 2b11202 commit 6ce8e50

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,10 @@ path = "examples/input/mouse_input.rs"
430430
name = "mouse_input_events"
431431
path = "examples/input/mouse_input_events.rs"
432432

433+
[[example]]
434+
name = "mouse_grab"
435+
path = "examples/input/mouse_grab.rs"
436+
433437
[[example]]
434438
name = "touch_input"
435439
path = "examples/input/touch_input.rs"

examples/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,7 @@ Example | File | Description
203203
`keyboard_modifiers` | [`input/keyboard_modifiers.rs`](./input/keyboard_modifiers.rs) | Demonstrates using key modifiers (ctrl, shift)
204204
`mouse_input` | [`input/mouse_input.rs`](./input/mouse_input.rs) | Demonstrates handling a mouse button press/release
205205
`mouse_input_events` | [`input/mouse_input_events.rs`](./input/mouse_input_events.rs) | Prints out all mouse events (buttons, movement, etc.)
206+
`mouse_grab` | [`input/mouse_grab.rs`](./input/mouse_grab.rs) | Demonstrates how to grab the mouse, locking the cursor to the app's screen
206207
`touch_input` | [`input/touch_input.rs`](./input/touch_input.rs) | Displays touch presses, releases, and cancels
207208
`touch_input_events` | [`input/touch_input_events.rs`](./input/touch_input_events.rs) | Prints out all touch inputs
208209

examples/input/mouse_grab.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
use bevy::prelude::*;
2+
3+
fn main() {
4+
App::new()
5+
.add_plugins(DefaultPlugins)
6+
.add_system(grab_mouse)
7+
.run();
8+
}
9+
10+
// This system grabs the mouse when the left mouse button is pressed
11+
// and releases it when the escape key is pressed
12+
fn grab_mouse(
13+
mut windows: ResMut<Windows>,
14+
mouse: Res<Input<MouseButton>>,
15+
key: Res<Input<KeyCode>>,
16+
) {
17+
let window = windows.get_primary_mut().unwrap();
18+
if mouse.just_pressed(MouseButton::Left) {
19+
window.set_cursor_visibility(false);
20+
window.set_cursor_lock_mode(true);
21+
}
22+
if key.just_pressed(KeyCode::Escape) {
23+
window.set_cursor_visibility(true);
24+
window.set_cursor_lock_mode(false);
25+
}
26+
}

0 commit comments

Comments
 (0)