Changing MouseMode not working properly

Godot Version

4.7

Question

Any ideas why this does not work?
I start off with MOUSE_MODE_CAPTURED, and can switch to MOUSE_MODE_VISIBLE.
Once that happens, when I use “cancel_mouse” it only returns MOUSE_MODE_CAPTURED (the print statement executes) no matter how many times I try, but it is not actually Captured - it remains Visible.

func _ready() -> void:
	Input.mouse_mode = Input.MOUSE_MODE_CAPTURED

func _input(event: InputEvent) -> void:
	if event is InputEventMouseMotion:
		if Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
			mouse_motion = -event.relative * 0.001
	if event.is_action_pressed("cancel_mouse"):
		if Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
			Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
			print("visible")
		else:
			Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
			print("captured")

Because you’re only running the code that changes it when the mouse mode is captured, which it never is after you release it.

try

if event.is_action_just_pressed("cancel_mouse"):

DUH!

Any suggestion on how to make this work?

func _ready() -> void:
	Input.mouse_mode = Input.MOUSE_MODE_CAPTURED

func _input(event: InputEvent) -> void:
	if event is InputEventMouseMotion:
		if Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
			mouse_motion = -event.relative * 0.001
	if event.is_action_pressed("cancel_mouse"):
		if Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
			Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
			print("visible")
		elif Input.mouse_mode == Input.MOUSE_MODE_VISIBLE:
			Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
			print("captured")

Try that. Though now that I think of it your code should’ve worked.

What keys/buttons are mapped to the “cancel_mouse” action?

I mapped the ESC key.

I tried a different key and the result was the same.

I also tried putting the code in “_unhandled_event”, and “_process” - no luck.

Not sure why either. Although I suspect it is because you were somehow blocking that key from getting to the player script.

Not intentionally - no code to that effect.

But then, the order of Scenes and their events is still a bit confusing to me, so it probably has to do with that.

If you are using any Control nodes in your player scene, or a CanvasLayer they can block key presses unless you allow them through.

True, but I’m not using any here - I’m doing test scenarios with minimal data.

Ok, I found the solution.

I had put the original posted code in my Player script.

When I moved it to my Main Scene script, it works fine.

Although I’m not sure why…