Setting Z-Index of actors according with their position (Reordering Depths).


  • Posts: 204
I'm not sure if this qualifies as a Shared Resource, but I don't know where else to post it. I have lot of actors on my scene and I wanted to arrange them using the Y-coordinate of each one. Becasue of the perspective I'm using, an actor with a higher Y value should always appear in front an actor with a lower Y value. I tried creating  a Map populated with all my actors and a their respective Y-coordinates, but it was really messy. I used the Array.sort(function) method, and it worked but I wanted something cleaner.

Then I found this:

It was exactly what I was looking for, using a simplier and cleaner method, so I implemented it on my game.

As you can see on the attached file (image only), I created a custom event called "ArrangeDepths", where I populate a list with all the actors that I need to sort - All the "TestTile" actors.

Then I call and Array.sort() method, that triggers the "sortByY" function, which compares a couple of items and returns an integer as a result. The returned value tells the Array.sort() method wheter the first item is greater than, less than or equal to the second item, and the method runs this function as many times as it needs to sort all the items.

Finally we take the sorted Array/list, and for each item we set its depth according with its place in the Array/list. Note that I didn't use the haxe "setChildIndex" methods, but Actor.setZIndex(index) instead.

Works like a charm for me (Sorting only 37 actors), and I thought it could be useful for someone else, so I wanted to share it. I'm sure you can adapt it for your own needs, for example: populating the list in a different way, sorting inside an update event or comparing X-coordinates instead.

Sorry for my English.


  • Posts: 150
Thanks a lot for sharing this! I was just in the process of making a behaviour for the same purpose and now I stumbled upon this. It is much simpler and works incredibly well!