Implementing clickable sprites

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

Hello,

i am looking for an efficient way to make some 2D sprites clickable / react to mouse inputs. I found this code snippet online:

===================
extends Sprite

func _unhandled_input(event):
if event is InputEventMouseButton and event.pressed and not event.is_echo() and event.button_index == BUTTON_LEFT:
var pos = position + offset - ( (texture.get_size() / 2.0) if centered else Vector2() )
if Rect2(pos, texture.get_size()).has_point(event.position):
print(‘test’)
get_tree().set_input_as_handled()

===================

I tested this with an centered 64x64 rectangle as a sprite. The code itself worked, but unfortunately the Rect2 object created in the script is a bit off on the y-axis and does not fit the sprite. I tried to fix this by manually adjusting the position of the Rect2 object, but the adjustment would have to be made for each other sprite individually.

Do you know a solution to this problem or a better way to select sprites per mouse click?

:bust_in_silhouette: Reply From: kidscancode

Use an Area2D. You get input handling with CollisionObject2D signals like input_event and mouse_entered/exited.

Alternatively, use a TextureRect and you get all the Control node input handling.

I just got done debugging a related issue – Help debugging clickable sprites? - Godot Forums . Using Godot 3.6 on 9/24/22, I needed to use a Panel (and its gui_input signal) rather than an Area2D as the sprite’s parent.

PorotisDev | 2022-09-25 02:07