Emulated mouse click not pressing buttons

Godot Version

4.3

Question

I’ve got this script:

func _process(delta: float) -> void:
	if Input.is_action_just_pressed("ui_accept"):
		var click := InputEventMouseButton.new()
		click.set_button_index(MOUSE_BUTTON_LEFT)
		click.set_pressed(true)
		Input.parse_input_event(click)

func _on_button_pressed() -> void: #connected to $Button.pressed
	print("How dare you press me!?")

attached to a node in my scene.
This script emulates left mouse clicking and it does interact like normal mouse click with all the other nodes in the scene except for the UI’s buttons. In fact, it activates the visual effect of the pressed button but it doesn’t actually press it (the output doesn’t print the message), while if I click the button with the mouse it prints the message normally. How can I make this script emulate press mouse button exactly like it was actually pressed?
Thanks in advance!

EDIT: Button.action_mode was also set to ACTION_MODE_BUTTON_PRESS

Only write _on_button_pressed() in code for connect:

func _process(delta: float) → void:
  if Input.is_action_just_pressed(“ui_accept”):
    var click := InputEventMouseButton.new()
    click.set_button_index(MOUSE_BUTTON_LEFT)
    click.set_pressed(true)
    Input.parse_input_event(click)
    _on_button_pressed()

func _on_button_pressed() → void: #connected to $Button.pressed
  print(“How dare you press me!?”)

combining with @Mahan’s response, i would simulate the full mouse click motion of pressing and unpressing but also, I don’t see where you are positioning the simulated mouseclick? Don’t you want the simulated mouse to be positioned right on the button?

func _process(delta: float) → void:
  if Input.is_action_just_pressed(“ui_accept”):
    var click := InputEventMouseButton.new()
    click.set_button_index(MOUSE_BUTTON_LEFT)
    click.position = Vector2(500, 500) # Where should your simulated mouse click?
    click.set_pressed(true)
    Input.parse_input_event(click)

    click.set_pressed(false) # Let's let go of the mouse click
    Input.parse_input_event(click)

    _on_button_pressed() # Maybe you don't need this anymore if the simulated mouse is positioned correctly?

func _on_button_pressed() → void: #connected to $Button.pressed
  print(“How dare you press me!?”)
1 Like

It worked by just setting the event position, so this is the new code:

func _process(delta: float) → void:
     if Input.is_action_just_pressed(“ui_accept”):
     var click := InputEventMouseButton.new()
     click.set_button_index(MOUSE_BUTTON_LEFT)
     click.position = get_viewport().get_mouse_position()
     click.set_pressed(true)
     Input.parse_input_event(click)

This worked perfectly

Thanks you anyway!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.