Using Controller button in place of mouse left click

Godot Version

Godot 4.2

Question

So, I’m trying to get a controller button press to work as a mouse click so I can click on UI objects. I’m also trying to NOT use the focus system right now. Just want “Push X button → left mouse click” (for all intents and purposes)

Here’s the code I’m using, but it doesn’t seem to work. The buttons will flash for a moment as though they had been clicked, but nothing changes. The fact that the buttons are responding, but not actually doing anything, proves to me that it’s not another UI object intercepting the Input call.

The buttons, themselves, are using the “pressed()” signal and otherwise work fine when clicked on with a mouse.

Here’s my code:

 if event is InputEventJoypadButton:
      var isJoyPressed: bool = false
      var focus_owner = get_viewport().gui_get_focus_owner()
      if focus_owner:
          focus_owner.release_focus()
        
    if Input.is_joy_button_pressed(0,0) and !isJoyPressed:
        var JoyClick = InputEventMouseButton.new()
        JoyClick.button_index = MOUSE_BUTTON_LEFT
        JoyClick.position = get_viewport().get_mouse_position()
        JoyClick.pressed = true
        Input.parse_input_event(JoyClick)
        
        isJoyPressed = true
    else:
        isJoyPressed = false
1 Like

Then just set the button’s focus_mode to “None”. No need to get hacky.

You’re creating an artificial mouse button press, but, by default, the pressed signal will only be fired on button release. You can change this behavior by setting action_mode to “Button Press” instead.

So with those two properties (focus_mode, action_mode) set correctly, it’s just:

func _input(event: InputEvent) -> void:
	if event is InputEventJoypadButton and event.device == 0 and \
       event.button_index == JOY_BUTTON_A and event.pressed:
			var JoyClick = InputEventMouseButton.new()
			JoyClick.button_index = MOUSE_BUTTON_LEFT
			JoyClick.position = get_viewport().get_mouse_position()
			JoyClick.pressed = true
			Input.parse_input_event(JoyClick)

Thank you for this solution!

It works. :slight_smile:

1 Like