intersect_point : How to best manage overlapping bodies?

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

I’m using intersect_point to catch when the mouse pointer is inside an Area2D (and when it’s not).

When objects are overlapping, there are multiple results in the Array it returns. That’s fine, but I wish that there was a way I can control which object gets the priority. It would help if the object that is displayed on top is also the first one in the Array.
So far it seems that z-index or the position of the Node in the tree does not have any influence over where it will end up in the Array returned by intersect_point.

Any suggestions?

var space = get_world_2d().direct_space_state
var mousePos = get_global_mouse_position()
# Check if there is a collision at the mouse position. 2 hits max.
var result = space.intersect_point(mousePos, 2, [], 2147483647, true, true)
if result.empty():

  # We measure a max of 2 hits
  if result.size() == 2:
    # If we found overlapping objects, an Actor will "win" the mouse-over.
    # TODO: We can also define other priorities. Maybe the Z index? Or a setting?
    var c2 = result[1].collider.get_owner()
    if c2 is Actor:

var c = result[0].collider.get_owner()
if c is Actor or c is ScreenRegion or c is RoomObject:
:bust_in_silhouette: Reply From: jgodfrey

While I don’t know any details regarding the order of the returned array, I’d guess you could easily sort it however you want/need via Array.sort_custom()

I could indeed sort the Array, or iterate through it while looking for the criteria that defines the priority. But I’d rather not do that each frame because I’m afraid it will affect performance.

So I was hoping there is a setting I’m not aware of, perhaps in the Area2D or the CollisionShape that has an influence over what the ray will hit first. For example, the Priority setting on the Area2D. Or the Z-Index.

So far it doesn’t seem to make a difference if I change them. I guess it’s totally random which objects are hit first?

Erwin Broekhuis | 2020-12-31 12:09