Z ordering (Y-sorting) sprites

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By batmanasb
:warning: Old Version Published before Godot 3 was released.

I’m making a 2D RPG and need to sort all sprites in the scene by their Y axis so that things on the bottom overlap things on top. Is there an way to do this in Godot? I noticed some old forums recommend the YSort node but as you can see the documentation is kinda empty and doesn’t explain what it is. My guess is that it sorts the Z value of all it’s children based on their Y position, but I’m not sure.

Here’s the code I’m currently using:

#order the z layers based on height
func zOrdering():
	#object's height = y coordinate - bottom of it's sprite
	var characterBottom = bodySprite.get_item_rect().size[1] * 0.5
	var heightOnCanvas = get_global_pos()[1] + characterBottom
	set_z(int(heightOnCanvas))

It literally sets the Z value to the Y position of the bottom of the sprite, this way I can stand in front of trees and move behind them, all with having one sprite for each tree. I found this method from a Unity tutorial.

However, it doesn’t work so well in Godot because the maximum Z value seems to be 4096, so once my character goes too far away from the center of the scene, it starts getting errors.

Does anyone know a better way to Y sort in Godot, or how the YSort node works?

:bust_in_silhouette: Reply From: The_Duskitty

Well i mean, if you mean layer wise, the heiarchy is already sortable by layer, so you should in theory be able to sort things via that (Lower is Closer to the Camera, Higher is further back)

Yeah but only if it’s between 4096 and -4096, or else it gives me an error. for example: set_z(1000000) doesn’t work.

batmanasb | 2016-03-28 17:29

:bust_in_silhouette: Reply From: CowThing

The YSort node will automatically sort all of its children nodes as long as sort is enabled. So you can make a Ysort node and name it something like “Objects”, then add all of your objects to that node.

Will it work for children of children?

batmanasb | 2016-03-28 17:31

Okay it doesn’t work for children, so I had to combine a few categories into one, but that’s fine. Now I have a small issue where I used a Z value in an animation to move a weapon sprite in front or behind the player sprite. Is there a way to switch the order of the node hierarchy by moving a node around through code?

batmanasb | 2016-03-28 18:34

:bust_in_silhouette: Reply From: kroket

if anyone is still struggling with this: you can just put

for obj in object_array:
	
	obj.z_index = obj.position[1]*0.1

to get 10x the amount of possible z indexes