Gabor Lengyel
Gabor Lengyel

Reputation: 15598

Which Control sent an InputEvent in Godot 4

Using Godot 4.1, I am trying to achieve the following. I dynamically create some TextureRect nodes, and then assign handlers to mouse clicks, like this (just for the example):

var tr = TextureRect.new()
# ...
tr.gui_input.connect(_on_texture_rect_gui_input)

According to the docs, the handler receives one parameter, the event itself. So I have this handler:

func _on_texture_rect_gui_input(event: InputEvent):
    if event is InputEventMouseButton:
        if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
            print("Image clicked, but which one?")

But as said above, I create many of these TextureRect objects dynamically. How do I know which one received the click?

InputEvent does not seem have this info (like sender is common in some other languages), and I have no other ideas tbh. :) This makes me think I'm doing something fundamentally wrong. How am I supposed to do this properly?

One idea I had was that I could connect the event on the container, and not on individual images. That way when the container event fires, I guess I could find out which image received the click, based on the click and image coordinates. But this is really messy, there must be a better way.

Upvotes: 1

Views: 788

Answers (1)

SilicDev
SilicDev

Reputation: 354

When connecting the singal you could use Callable.bind() on the receiving method to add the texture rect as a parameter, i.e. tr.gui_input.connect(_on_texture_rect_gui_input.bind(tr)). Parameters bound with this method will be added to the end of the parameter list so the _on_texture_rect_gui_input should look something like this:

func _on_texture_rect_gui_input(event: InputEvent, image: TextureRect):
    if event is InputEventMouseButton:
        if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
            # use image for processing of the input

Note that when you default image to a value you can also connect without the additional bind. In that case image will be that default value.

Upvotes: 3

Related Questions