+5 votes

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

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?

in Engine by (852 points)

3 Answers

–3 votes

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)

by (483 points)

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.

+6 votes

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.

by (676 points)

Will it work for children of children?

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?

0 votes

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

by (20 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.