Tainted\\Coders

Confine the cursor to a window

Bevy version: 0.16Last updated:

Set the CursorOptions on the Window to CursorGrabMode::Confied.

use bevy::prelude::*;
use bevy::window::{CursorGrabMode, CursorOptions};

fn main() {
  let window = Window {
    cursor_options: CursorOptions {
      grab_mode: CursorGrabMode::Confined, // Enable cursor confinement
      ..default()
    },
    ..default()
  };

  App::new()
    .add_plugins(DefaultPlugins.set(WindowPlugin {
      primary_window: Some(window),
      ..default()
    }))
    .run();
}

This currently has poor cross-platform support and won't work on macOS.

The cursor grab mode can also be easily overwritten from a system if you need something more dynamic:

// https://github.com/bevyengine/bevy/blob/v0.16.1/examples/input/mouse_grab.rs
// This system grabs the mouse when the left mouse button is pressed
// and releases it when the escape key is pressed
fn grab_mouse(
  mut window: Single<&mut Window>,
  mouse: Res<ButtonInput<MouseButton>>,
  key: Res<ButtonInput<KeyCode>>,
) {
  if mouse.just_pressed(MouseButton::Left) {
    window.cursor_options.visible = false;
    window.cursor_options.grab_mode = CursorGrabMode::Locked;
  }

  if key.just_pressed(KeyCode::Escape) {
    window.cursor_options.visible = true;
    window.cursor_options.grab_mode = CursorGrabMode::None;
  }
}