Search Unity

Top-Down View Depth

Discussion in '2D' started by Trexug, Dec 2, 2013.

  1. Trexug

    Trexug

    Joined:
    Dec 2, 2013
    Posts:
    88
    I am messing around with the 2D functionality of Unity and want to create a top-down view similar to that of games like Prison Architect. For that I need a bit of ordering so that entities standing behind other entities are drawn first, giving the the impression of depth.

    My naïve solution is to place entities (like objects, walls, characters etc.) on the same Sorting Layer and use the Order in Layer property to control drawing order. Entities near the top of the screen (high y-value) are drawn first to make them appear farther away. Below is my very simple code.

    Code (csharp):
    1. using UnityEngine;
    2.  
    3. [ExecuteInEditMode]
    4. [RequireComponent(typeof(SpriteRenderer))]
    5. public class UpdateOrder : MonoBehaviour {
    6.  
    7.     private SpriteRenderer cachedSpriteRenderer;
    8.  
    9.     private void Start () {
    10.         cachedSpriteRenderer = GetComponent<SpriteRenderer> ();
    11.     }
    12.  
    13.     private void Update () {
    14.         cachedSpriteRenderer.sortingOrder = -Mathf.RoundToInt(transform.position.y * 100);
    15.     }
    16. }
    17.  
    I have tested it out, it works and provides the functionality I would like, but I can't help wondering: Is there a built-in or better way of doing this?
     
  2. unitylover

    unitylover

    Joined:
    Jul 6, 2013
    Posts:
    346
    The way you are doing it is the way I would do it. I do not know of any other way to do it other than manually setting the order in the layer in the inspector. If you're dynamically creating sprites however, your method should be just fine.
     
  3. Trexug

    Trexug

    Joined:
    Dec 2, 2013
    Posts:
    88
    Thanks for the reply. I am not creating sprites dynamically at the moment but I am moving them around, so I need the sorting order to update. However, now that you mention it, I guess it would make sense to treat static objects differently. Once their sorting order has been set, it will never change, so there is no need constantly update it. I think I will limit the use of that script to entities that actually change position and set the order of non-moving objects through the editor or through a script that only does sets it on start.
    Glad to know I am not totally off the track. I'll do it this way until/unless someone has a better idea :)
     
  4. unitylover

    unitylover

    Joined:
    Jul 6, 2013
    Posts:
    346
    If it works and gets the job done to your liking, you're doing just fine.