Order by layer

Hello guys am currently setting my order by layer for ‘static’ objects based on there y position with a script and i update my players order in layer dynamicly, this works really well.
But now if am on the side of an object with the player on the same layer its behind the objects how would i go about fixing this, under this text there is a gif about what i mean

I know i could change the sorting layer to always draw the player on top but that doesnt sort my issue

Do your sprites sort using pivot? Perhaps set that sprite’s pivot to the middle so your player’s Y isn’t greater unless he’s above the midpoint rather than the bottom?

Try to imagine where the object would be touching the ground if it were 3D, and place the pivot in the center of that space. I find that to be a good middleground for being able to overlap the object while still making sense in the 2D depth illusion.

public class SortingOrder : MonoBehaviour
{
    [SerializeField]
    SpriteRenderer spriteRenderer;
    [SerializeField]
    bool dynamicOrder;

    void Start()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        //Takes the current y position and multiplies it by -10
        //We use -10 instead of -1 to actually make a difference between 2, 2.3 etc
        //* 10 will output 22 instead of 2
        //This will make it so the sorting layers are properly done
        spriteRenderer.sortingOrder = (int) (transform.position.y * -10);
    }

    private void LateUpdate()
    {
        //Checks if it should dynamicly update the object (example: player) and if its visible for the camera
        if (dynamicOrder && spriteRenderer.isVisible)
        {
            spriteRenderer.sortingOrder = (int) (transform.position.y * -10);
        }
    }
}

This is the current script i place on my player/game objects like the chest/sign (objects that are interactable)

Thanks for sharing that. You can actually accomplish this in a more global capacity by using the Transparency Sort Axis. That can make your default sorting use the Y axis instead of Z. So if all your renderers were at sorting order 0, they will order themselves based on the axis you set there. That’s a common way to handle sorting for a 2D game like yours, so maybe that will help. Check out this video for more info:

My comment about pivots is related to the SpriteRenderer setting “Sprite Sort Point”, which you can configure to sort by the centerpoint or the pivot point of a sprite:

Hopefully you can use this info to get the behavior you’re looking for.

1 Like

Sorry i never noticed you asnwerd, your idea works really good thanks man! Noticed it as i was running into a problem the way i was doing it in my multiplayer test run

1 Like