Language

How do I make the player sprite on top of the object when the player is above it but below the object when the player is below it?

So i'm making a top-down RPG game and I want the player to appear behind the tree (like shown in the first image). But the problem is, I want to make the player above the tree when they are in front of it. If you look at the second image, the tree will be over the player when I want it to be under them. How can I fix this?

1 Reply

New answer with an interesting idea - may not be the best. The idea stems around the idea that the y position of the character determines if it's behind a tree or not. If the y of the character is greater than that of the tree, then the character should be behind it - and vice versa. So...

using UnityEngine;
/// <summary>
/// A singleon manager that has a reference to the player
/// </summary>
public class TreeSortManager : MonoBehaviour
{
// Singleton
static TreeSortManager instance; // we keep a reference to our own script... its static
// Use static property to use the reference to this script, giving access to variables, methods, etc.
// It similar to how you would use a static class
public static TreeSortManager Instance
{
get
{ // reference will always be null, until we find one
if (instance == null)
{
// search our scene with this script and reference it
instance = (TreeSortManager)FindObjectOfType(typeof(TreeSortManager));
}
return instance;
}
}
[SerializeField] GameObject player;
public GameObject Player { get { return player; } }
}

I created a manager (you probably have one) that has a reference to the character. I just made a simple singleton and reference the character to it in the inspector.

Then I created a TreeSort class that is on every tree. All it does is determine if the tree should be behind the player (or front) via comparing their y position values.

The key here is that for my tests, the character and trees pivot points where in the center of the image. I think this is crucial in this idea working correctly, but even if they aren't, you can add some sort of offset.

Let me edit my generic singleton above with one you can just copy. Give me a few seconds.

A singleton just makes it so there will only ever be one of that script in your game. Right, so there is no reason to have another TreeSortManager. It also allows us to have instance access to the script via its static variable assigned to itself. Thus, you can do this TreeSortManager.Instance.Player - we get direct access to the manager (without getting a reference), so we can get the Player variable. Usually all your managers will be a singleton - also, you can just make a static class... somewhat similar.