- Home /
2D Top-Down 3D-Like effect
Hi, I'm making a 2D Top-Down game using Unity 2D. However, I've ran into a feature I want to add, but don't know how. Here's what I'm trying to do: When the player is in front of an object, they should be on top of the object in the sprite's sorting order., and when the player is behind an object, they should be below the object. How would I achieve this? Thanks
Search for "sprite depth sorting", there are lots of tutorials and samplescripts for this as it is a common feature of top-down 2d games. One way to do it is to check the character sprite's y value and use this to set it's renderer's sorting order.
Answer by Eidern · Aug 06, 2017 at 07:23 PM
Hello, I suggest you to have a look at the Unity 2D best practice showed here:(2014, i know but it fits perfectly for what you're asking) :
https://www.youtube.com/watch?v=HM17mAmLd7k
at 34:00, with a script onto the object which every update will compare the y.pos of it's Anchor and use it to change its z-index on the fly :
void Update(){
renderer.sortingOrder = (int)(transform.position.y * -10);
}
Like this, when you're object is got an y coord lower than the other objects it displays above, and when it's higher y it displays behind. But watch the video, there are some other nice tricks likeplaying with anchors for exceptionnal objects that you'd like to put on top even if they're higher..
Answer by moltow · Aug 06, 2017 at 05:50 PM
As @Cherno suggested, there are many ways to do this, but for the sake of the discussion, let's assume you're just using the Default SortingLayer. Further, let's assume that the bucket's OrderInLayer property is set to 1. You could then have your Character's script do something like:
SpriteRenderer renderer;
void Start ()
{
renderer = GetComponent<SpriteRenderer>();
}
void MoveSpriteToBack()
{
renderer.sortingOrder = 0;
}
void MoveSpriteToFront()
{
renderer.sortingOrder = 2;
}
How would I make this work for multiple objects at once?