Being able to create depth within a 2D scene was something we were all a little concerned about. Thankfully our worries soon were gone after we discovered the Sprite Sorting Layer options within Unity. Adjusting the sorting layer of a sprite allows us to place elements in the background, foreground, or anywhere in between, with a seemingly infinite number. Building a scene that has depth became much easier.
Thanks to the assets created by the team, we were able to quickly order the different background sprites so that it looks right, and matching the one created in Aesprite.

Having the elements of the scene on different sorting layers allowed us to position the player in between, and make it look like he is amongst the trees and bushes.
Great! Now we can focus on the important mechanics.
Nope.
We soon noticed that when the player takes the path down to the south, the sprite ends up being behind the foliage nearer the background. In order to fix this, we needed to detect when the player was walking down the path, and readjust it’s sorting layer so that it appears in front. Then, change it back again when the player walks back up.

We figured the best way to fix this was to add some triggers around the fork in the path that changes the sorting layer when it detects a collision with the player. Let’s call these triggers “door-mats” as they are kind of like a mat before entering the path. To do this, we created two empty game objects in the scene and added polygon colliders to each of them, and then adjusted their collider so that they fit within the path and don’t overlap with each other.

I then created a new C# script that can be applied to the player. The scripts main goal is to detect what the player has triggered and then apply the correct sorting order to it. I used Unity’s built-in callback method called OnTriggerEnter2D() which runs the code inside when a trigger is detected. Inside this method, I added an if statement that checks the tag of the object that has been triggered. If the tag is right, change the sorting order. If not, then nothing happens.
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "TriggerTop")
{
transform.GetChild(0).GetComponent<SpriteRenderer>().sortingOrder = 10;
}
if (other.gameObject.tag=="TriggerBottom")
{
transform.GetChild(0).GetComponent<SpriteRenderer>().sortingOrder = 13;
}
}
What’s great about this script is that it can be applied to any game object that can move between layers. We can add this script to the Monty game object so that when he follows the player to another section, his sprite is in the right position.