Handling sprite selection and deselection when on a tilemap (Godot 4 Beta)

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

I have an AnimatedSprite navigating on top of a TileMap. I’d like to be able to click the sprite to select it and click anywhere else on the tile map to deselect the sprite. I have the sprite’s property Pickable set to true. I can get deselection to work fine, but I’m having trouble with the selection. The problem is that I’d like the sprite to receive the click event first and prevent the tile map from getting the event. Here’s what I’ve tried.

Attempt #1

I tried using the _unhandled_input() method on the tile map, but the problem is that _unhandled_input() is called before _input_event() on the sprite. This seems to match the description in the docs (but I have to say, this seems to be an unusual design choice).

Attempt #2

I then tried adding a collision shape to the camera, and then binding any input event on that shape to the camera’s script. However, the behavior here doesn’t seem to match the docs. In the docs, it says “When sending events to all listening nodes within a scene, the viewport will do so in a reverse depth-first order”, but I observed the order was random. Not sure if this is a Godot 4 bug or not.

Any ideas on the best way to accomplish a simple sprite selection and deselection?