Hi, I'm trying to detect the top node that under the mouse hovers in 2D space. After a while seeks and testing, I got a solution by using intersect_point and assigning z_index for ordering nodes.

It works but it's quite hacky to me such as I need to put the max_results to a really high number in the real case because I need to compare all the z_index and the number of objects is dynamic changing. And if there is more than one node that has the same z_index and overlaps with each other, it might cause an error too.

Any better way?

extends Node2D

var top_z: = -1

func _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):
		var ob = space.intersect_point(mousePos, 10, [], 2147483647, true, true)
		for i in range(ob.size()):
			if i == 0:
				top_z = ob[i].collider.z_index
			else:
				if ob[i].collider.z_index > top_z:
					top_z = ob[i].collider.z_index
		print(top_z)

Is it possible to bind a point at the mouse position and then update the current possible collision nodes with collision detection. like this

extends Node2D
onready var mouse_point = $Point

var area_list = []
var top_z: = -1

func _physics_process(delta):
	mouse_point.global_position = get_global_mouse_position()
	for i in range(area_list.size()):
		if i == 0:
			top_z = area_list[i].z_index
		else:
			if area_list[i].z_index > top_z:
				top_z = area_list[i].z_index
	print(top_z)

func _on_point_area_entered(area):
	area_list.push_back(area)


func _on_point_area_exited(area):
	area_list.erase(area)

Also, the direct_space_state method is only safe in _physics_process. (https://docs.godotengine.org/en/3.4/tutorials/physics/ray-casting.html)

@vmjcv said: Is it possible to bind a point at the mouse position and then update the current possible collision nodes with collision detection.

Cool, I will give it a try, thank you very much.

7 months later