How To Move Mouse By Joystick

Godot Version

4.5.1.stable

Question

How do I get the mouse to move from a joystick input?

I need to be able to move the mouse cursor by the input of a joystick.

I’ve written this script using things I’ve found on the docs

# get joystick axis strengths
	var joy_vector := Vector2(
		-Input.get_joy_axis(0, JOY_AXIS_LEFT_Y),
		Input.get_joy_axis(0, JOY_AXIS_LEFT_X)
	)
	
	# deadzones
	if abs(joy_vector.x) < 0.15:
		joy_vector.x = 0
	if abs(joy_vector.y) < 0.15:
		joy_vector.y = 0
	
	# move mouse
	var mouse_position := Vector2(DisplayServer.mouse_get_position().x, DisplayServer.mouse_get_position().y)
	mouse_position += joy_vector * delta
	
	# fence mouse position
	mouse_position.x = clamp(mouse_position.x, 0, DisplayServer.screen_get_size().x)
	mouse_position.y = clamp(mouse_position.y, 0, DisplayServer.screen_get_size().y)
	
	# set the mouse position
	DisplayServer.warp_mouse(mouse_position)

The problem with this code is that when you run it, the joystick always moves to the bottom-right. joy_vector reports (0, 0) when that happens. You even sometimes get into a softlock where you can’t close the editor even with f8.

Do DisplayServer.screen_get_size() and DisplayServer.warp_mouse() have different offset positions?

Is there another way I’m supposed to be moving the mouse?

Increase the deadzone threshold.

I’ve done that, and it still drifts the mouse. I noticed something new, though. When the mouse moves with no input, joy_vector is (0, 0). Do you know if this means DisplayServer.screen_get_size() and DisplayServer.warp_mouse() have different offset positions?

warp_mouse() is in window client space while mouse_get_position() is in screen space. Try subtracting window_get_position() from the argument you send to warp_mouse()

1 Like

Thank you so much!