Ordering z-values of all objects in a layer, help!

Hello,


I have a bunch of monsters added to my game with my Monster class.


I am looking for a formula to sort through y-values + modify all the z-values of the monsters so the ones at the bottom of the screen appear to be closer than those at the top.


To access my monsters in my monster array I would do so like this:


for monster in Monsters{

}


I could easily create a function that could return the y-value of each monster and add it to an array... But I don't know where to go from there. Anyone able to write up a formula I could use? It seems like something fairly simple but for some reason its not coming to me.


Even if I had an array of each of the monsters y-values, I don't know how I would re-assign the z-values? I am confused.

Answered by sleeper in 38720022

Assuming your Monster class is derived from SKSpriteNode and you have an array,

x
, of them, you can do this


let y = x.sort({$0.position.y > $1.position.y}) 
for i in 0..<y.count {
y[i].zPosition = i
}

I assume you have a way to get to the SKSpriteNode for each monster. To adjust the z-value, you'd set the node's zPosition property. (The zPosition is not inherited by sub-nodes, so if there are any visible sub-nodes, you'll have to adjust their zPositions also.)


The easiest thing to do might be simply to set the zPosition to -position.y. That will make the nodes towards the top of the scene far away, and nodes towards the bottom nearer. Of course, any nodes behind the monsters would then need to have a zPosition farther away than any of them.


If you wanted a tighter spread of zPosition, just sort the monsters by position.y and give the monster at index i a zPosition of monsters.count - i. (You can multiply by 5 or something if you want each monster to have a range of zPositions so that subnodes can be displayed properly relative to each other.)

My problem is that I don't know how to:


A) sort the z-position of each node

B) re-order them


If someone could write out a piece of code to help, I would appreciate that.

Accepted Answer

Assuming your Monster class is derived from SKSpriteNode and you have an array,

x
, of them, you can do this


let y = x.sort({$0.position.y > $1.position.y}) 
for i in 0..<y.count {
y[i].zPosition = i
}
Ordering z-values of all objects in a layer, help!
 
 
Q