Detect clicked sprite in C#

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

Hi,

I’m trying to figure out how to detect what is being clicked on… it’s easy to find solutions for this online, e.g.:

extends Area2D

func _input_event(viewport, event, shape_idx):
    if event.type == InputEvent.MOUSE_BUTTON \
    and event.button_index == BUTTON_LEFT \
    and event.pressed:
        print("Clicked")

But how would that get converted to C#? I’ve been trying to play around with it and can’t seem to find the same arguments (event and shape_idx specifically).

Could anyone lighten this up? :slight_smile:

:bust_in_silhouette: Reply From: Zylann

The code you found was for Godot 2. It has changed in Godot 3.

In C# it would be something like:

void _InputEvent(Viewport viewport, InputEvent ev, int shape_idx) {
	
	var btn = ev as InputEventMouseButton;

	if(btn != null && ev.ButtonIndex == ButtonList.Left && ev.Pressed) {
		GD.Print("Clicked");
	}
}

Note: maybe you will need to cast ButtonList.Left to int, but I’m not sure since I don’t use C# in Godot yet.

will try this asap :slight_smile: thanks

Christoffer Schindel | 2018-08-09 23:43

:bust_in_silhouette: Reply From: Christoffer Schindel

With the help of Zylann, I came up with this:

private void _on_Area2D_input_event(Viewport viewport, InputEvent @event, int shape_idx)
    {
        if (@event is InputEventMouseButton btn && btn.ButtonIndex == (int)ButtonList.Left && @event.IsPressed()) {
            GD.Print("Clicked");
        }
    }

in Godot 4.2.2 instead with MouseButton.Left