Mouse keeps escaping capture

Godot: v4.7.2

OS: Manjaro

I am having problems with my mouse regularly escaping from it’s captured state. This happens when I move the mouse up and the cursor goes on my taskbar, or to the right and the cursor enters my second screen. Looking down and to the left, where the cursor would just been hitting the edge of the current screen, causes no problems.

This also doesn’t happen all the time. Some 10% of the times I run a scene, the mouse gets properly captured and never escapes.

Here’s the complete camera control script:

extends Node3D

var sensitivity = 0.2

func _ready() → void:
  Input.mouse_mode = Input.MOUSE_MODE_CAPTURED

func _input(event: InputEvent) → void:
  if event is InputEventMouseMotion:
    get_parent().rotate_y(deg_to_rad(-event.relative.x * sensitivity))
    rotate_x(deg_to_rad(-event.relative.y * sensitivity))
    rotation.x = clamp(rotation.x, deg_to_rad(-90), deg_to_rad(90))

Any idea how to keep the mouse actually captured to the game in the game window?

On Linux with two screens this is very often a focus issue rather than a bug in your code. Setting Input.mouse_mode in _ready can run before the window really has focus, so try setting it again when the window gets focus back, for example in _notification with NOTIFICATION_APPLICATION_FOCUS_IN, or simply on the first mouse click. It is also worth checking whether your session runs X11 or Wayland, then launching the game with --display-driver x11 or --display-driver wayland to compare, because pointer capture is handled quite differently by each. If it only escapes on one of them, you at least know it is the compositor side and not your script.

I see.

The mouse gets properly captured when I click on the titlebar on top of the window running the game. But it doesn’t if I click with the mouse in the viewport. That’s what probably caused the 10% of cases where the mouse did get captured.

Adding _notification for this appears to not be necessary. But it also doesn’t help with having the mouse captured on start.