How do i check if a sprite is clicked?

Godot Version

4.4.1

Question

Hi, so I wanted to check if a sprite clicked then a number would go up, and I got it kinda working but like it makes the number go up when you click any where not just the sprite, And the is_pixel_opaque does not work anymore, I am new to godot but i know some lua.

extends Node2D

var Cookie = 0

# Called when the node enters the scene tree for the first time.
func _input(event):
	if event.is_action_pressed("Click"):
		print(Cookie)
		Cookie += 1
		print(Cookie)

You could add an Area2D and connect to it’s input_event signal to detect clicks, the _input function does not check position, only inputs.

Note that the comment above the _input() function is misleading.

_input() is not Called when the node enters the scene tree for the first time.

Please save yourself (and other readers of your code) from future confusion and remove that comment line.

Probably it is just a remnant from the original script template.

3 Likes

maybe you could add a button to check if somethings being pressed and hide it so it is not visible on screen.

As @gertkeno said, Area2D provides you a _input_event to do your classic event checks. Or, the idea of @thegamenerd that you can use the Button or TextureButton node.

Though these button nodes are Control nodes (UI nodes), but since they all inherits from CanvasItem to be drawn on a 2D canvas, so this approach is pretty nice, as I believe everybody would use a Label node to display a text in non-UI scenes.

Hi, I think as a beginner, name of the function _input can be misleading.

It doesn’t mean that… the _input function will be called when you click on the node. It just means that, for any input event anywhere in the game, it will recieve the input event and call the _input function on that node, regardless of if you click on it or not.

So that’s why you are seeing the number go up wherever you click, not just on the sprite.

The solutions propsed by the other people before my reply should hopefully help you.