How can you get a node from a mouse collision?

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

I have a board with cells(spaces), each of which is a node. When the mouse hovers over a cell, I want a variable to be assigned that node. As of now, the mouse can detect when it is hovering over an area, but that’s it.

func _physics_process(delta):

    var space = get_world_2d().direct_space_state
    var mousePos = get_global_mouse_position()

    if space.intersect_point(mousePos, 1, [], 2147483647, true, true):
	  cell = space.intersect_point(mousePos, 1, [], 2147483647, true, true)
	  cell = null

I think cell[0].collider is what I was looking for.

John97 | 2021-04-26 19:02

:bust_in_silhouette: Reply From: timothybrentwood

i would suggest making your cells be Area2Ds instead of Nodes. from there you can connect the “mouse_entered” and “mouse_exited” signals. for example:

extends Area2D

var my_variable = null

func _ready() -> void:
    self.input_pickable = true
	self.connect("mouse_entered", self, "_on_Area2D_mouse_entered")
	self.connect("mouse_exited", self, "_on_Area2D_mouse_exited")

func _on_Area2D_mouse_entered() -> void:
	my_variable = "entered"
func _on_Area2D_mouse_exited() -> void:
	my_variable = "exited"

They are actually 2DNodes, not plain nodes. I am already using that method actually, but because a cell is entered at the same moment it is exited, the variable is often mistakenly assigned null. I want the mouse to find out the cell to avoid this. Do you know how I can do this?

John97 | 2021-04-26 18:39

you could add

yield(get_tree().create_timer(0.35), "timeout")

at the start of the _on_Area2D_mouse_exited() to set the variable after a short delay upon the mouse exiting the node or you could call the function directly from the _on_Area2D_mouse_entered() function:

func _on_Area2D_mouse_entered() -> void:
    my_variable = "entered"

func use_my_varible():
    var stuff = my_variable

timothybrentwood | 2021-04-26 19:52