Get nearest Area2D on mouse enter/click

Godot Version

4

Question

I have a number of overlapping Area2D in a scene with picking enabled. Which Area2D receives mouse events seems arbitrary but I would like the Area2D closest to the mouse to receive the events. Is this possible?

You can use Viewport.physics_object_picking_sort to get the top-most Area2D of the stack.

For example:

extends Node2D

func _ready() -> void:
    get_viewport().physics_object_picking_sort = true
1 Like

Thanks,

Maybe I’m missing something or I didn’t make my question clear enough but I don’t think this solves the problem.

Ideally I want to highlight the sprite attached to the Area2D that is closest to the mouse and if the user clicks, I want the click event to go to that node only. Maybe it’s not possible using picking and I have to implement it myself?

Physics picking only tracks, if the mouse is or is not over a CollisionShape2D of the Area2D. Its calculations aren’t based on distance to the CollisionShape2D. You will need to track the distance yourself.

1 Like

Thanks, I guess there’s no way to do this from inside the individual area nodes (because each one is unaware of the others). It seems like I pretty much have to ditch picking and input events altogether and implement my own algorithm. E.g. Have some component that fills the screen and gets all the mouse events and does some kind of hit test on all the candidates then picks the closest.