Get mouse click position on the editor canvas

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By sygi

I have a TextureRect. I would like to be able to click on a picture inside the editor’s canvas and change the property on the TextureRect based on it.

I tried the following:

extends TextureRect

func _ready():

func _input(event):
    print("input", event.as_text())

But the inputs were only passed in-game, not in-editor. I also tried adding a separate plugin as a subclass of EditorPlugin and it’s able to intercept in-editor clicks and which object is selected, but the clicks’ positions are in global coordinates and I’m not able to translate back (as the position of my TextureRect is in game coordinates, not the editor ones).

I also looked at this question and found canvas_item_editor_viewport in the code, but I don’t think I have access to it from GDScript in editor.

Any idea how to do this?

It seems I moved a little by extending an EditorPlugin and forward_canvas_gui_input which gives me clicks wrt canvas viewpoint. I am still unable to recalculate them in the local coordinates.

sygi | 2021-03-07 17:06

:bust_in_silhouette: Reply From: code

Hi, instead of that code, i will advice you to use this

func _input(event):
       if event is InputEventMouseButton:
               if event.is_pressed():
                   var rect = $("path to the texture).get_rect()
                   if rect.has_point(event.position):
                       put your code here

Thanks for looking at the question: the problem is not what to do with the event once it’s there: in the given example, the click events are not processed at all in the editor.

sygi | 2021-03-07 16:16

:bust_in_silhouette: Reply From: sygi

Ok, I think I managed to do as:

onready var current_object: MyClass = null
func forward_canvas_gui_input(event):
    if event is InputEventMouseButton:
        var mouse_pos = current_texture.get_local_mouse_position()
        assert current_object is MyClass
        assert current_object.has_method("pass_click")
        current_object.field = mouse_pos
    return false

func handles(object):
if object is MyClass:
        current_object = object
    return object is MyClass

However, when I tried to pass the information through a method (and not a field), I got:

Invalid call. Nonexistent function 'pass_click' in base 'TextureRect ('.

My script looks like this:

class_name MyClass
extends TextureRect

export var field = 7
func pass_click(event):
    print("got event", event)

Oook, it seems it’s a lack of tool and mentioning the function exists is a bug.

sygi | 2021-03-07 17:32