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)