How do you check if the point underneath your cursor is empty from any object?

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

I’m creating a farm sim where you can build and place anything as long as there is nothing underneath your cursor. When something is underneath your mouse cursor, it will set “building_obstructed” variable to true so you can’t put something in that place.

The problem is, I don’t know how to check whether under cursor is empty.
I already tried mouse_entered() and mouse_exited() signals to toggle “building_obstructed” state:

func _on_mouse_entered():
     building_obstructed = true

func _on_mouse_exited():
     building_obstructed = false

But it will create problems when dealing with adjacent objects (e.g once the mouse cursor exited one area and go for another right next to it, the “building_obstructed” state stays “false”)

And no, using “area” argument of Area2D also yield the same thing

Is there any workaround for this?

Raycast for point or Shapecast if you want check bigger area

Moreus | 2023-04-25 08:53

But it will create problems when dealing with adjacent objects (e.g once the mouse cursor exited one area and go for another right next to it, the “building_obstructed” state stays “false”)

Hmmm… That would seem to imply that the mouse_entered signal for the “just entered object” is fired before the mouse_exited signal is fired for the “just exited” object.

What happens if, rather than tracking a boolean value, you instead use a counter that increments when the entered signal fires and decrements when the exited signal fires (similar to reference counting).

Then, as long as the counter > 0, you’re “over” something.

I don’t know whether that’ll work or not, but it should eliminate the problem you mentioned (and I quoted) above…

jgodfrey | 2023-04-25 16:48

@Moreus Shapecast2D works perfectly, thanks! I wonder why they put this node function separately from Area2D or CollisionBody2D…

@jgodfrey tried that; Unfortunately if the signal is fired too fast, you can land on “counter == 0” while something is already under your mouse cursor. Guess I’ll go with the Shapecast2D solution.

Vectoraith | 2023-04-27 00:38