Getting the absolute Z-Index of a node

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

When “Z As Relative” is checked on for a Node2D, its Z-Index is computed relatively to its parent’s. So if I have a scene tree like this

  • NodeA: Z-Index = 2
    • Node B: Z-Index = 3

Node B’s Z-Index is 2+3=5.

However, in a much more complicated tree, it might be a bit complex to compute that absolute Z-Index. Is there a built-in way to obtain that absolute value as the engine would calculate it?

:bust_in_silhouette: Reply From: Bruno Ely

For now, here’s what I’m using:

static func get_absolute_z_index(target: Node2D) -> int:
	var node = target;
    var z_index = 0;
	while node and node.is_class('Node2D'):
    	z_index += node.z_index;
		if !node.z_as_relative:
		node = node.get_parent();
	return z_index;

It’s not thoroughly tested, but I fixed all bugs I noticed and tried to prevent any I could anticipate.

Excellent! This allowed me to switch a node to using global Z index so I could reparent it safely.

Hyper Sonic | 2023-05-11 20:40