I have a top-down 2D where the sprites can partially overlap.
I would like that they overlap so that the sprite with the lowest y-value is drawn last and the one with the highest y-value is drawn first.
This would obviously change dynamicly based on the position of the player ( I guess changing it for the player alone would be enough ).
How can I accomplish this dynamic change in the draw-order?
Create a method that uses the y value for the layer.
You should first order the list:
Transform[] sprites; // You get them all in the start
Array.Sort(sprites, delegate(Transform go1, Transform go2) {
return go1.position.y.CompareTo(go2.position.y);
});
for(int i = 0; i < sprites.Length; i++){
SpriteRenderer sp = sprites*.GetComponent<SpriteRenderer>();*
sp.sortingOrder = i; } It might not be optimal to perform those eash frame, you’d rather call for those only when there is a movement of a sprite. You could use an event to trigger the call.