Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question 2D be in front or behind depending on the Y axis

Discussion in '2D' started by Notrain0, Mar 15, 2023.

  1. Notrain0

    Notrain0

    Joined:
    Feb 26, 2023
    Posts:
    7
    Hello,

    Sorry if this question already exists, I'm new to C# and new here and couldn't find the answer.
    Here is what I want to get :
    upload_2023-3-15_2-47-17.png
    upload_2023-3-15_2-47-33.png
    I want the game to say "Ok, his Y is higher so he'll be behind this enemy".
    Is it possible, and if so, how can I do this please ?

    Thanks !
     
  2. QuinnWinters

    QuinnWinters

    Joined:
    Dec 31, 2013
    Posts:
    490
    In an update function you need an if statement that compares the players y position to the enemies y position. If the players has a lower value, change the sorting order of the players sprite renderer to be higher than the enemies, and vice versa if the players position is higher than the enemies.
    https://docs.unity3d.com/ScriptReference/Renderer-sortingOrder.html
     
    Notrain0 likes this.
  3. Notrain0

    Notrain0

    Joined:
    Feb 26, 2023
    Posts:
    7
    Thanks for the answer, that makes much sense to me and is very clear !
    I'm going to do that as soon as I can :)

    But will it slow the program, or is it really soft ?
     
    Last edited: Mar 15, 2023
  4. karliss_coldwild

    karliss_coldwild

    Joined:
    Oct 1, 2020
    Posts:
    530
    Notrain0 and Daviiid like this.
  5. QuinnWinters

    QuinnWinters

    Joined:
    Dec 31, 2013
    Posts:
    490
    It does have some overhead, but I've never found it to have much of a negative impact, and occasionally I've done it to hundreds of sprites at a time.

    The sorting axis feature is great and works in a lot of situations, but it has the limitation of being global, so it won't work if you have groups of sprites you don't want to sort in the same manner as the rest.
     
    Notrain0 likes this.
  6. Notrain0

    Notrain0

    Joined:
    Feb 26, 2023
    Posts:
    7
    I see, thank you both for your answers, layering is the way too go, clearly !
    Thanks for documentation, too !
     
  7. flasker

    flasker

    Joined:
    Aug 5, 2022
    Posts:
    193
    you should use the transparency sort axis and sort by y, order in layer is limited to 60k positions instead of infinite, 60k positions is not enough, just think how many positions exist in between y= 0 and y =100, it looks like 100 but what about decimals? 0.1, 0.2, 0.3, 0.35 etc you cant fit 60k in there.

    The transparency sort axis is much superior
     
    Chubzdoomer likes this.