2D Layer Changing accordingly to player/monsters position.

Hello,

I am currently working on 2D game similiar to Binding of Isaac, however with more complex and different graphic. I am using unity 4, 2D ortographic mode & settings.

My problem lays in Layers order. If my hero is behind tree he should be covered by it. However if my hero comes from the bottom he need to cover the tree, that means tree layer must be changed. I don’t know how can i achieve this effect both for hero and every monster in game.

The changing point is when feet collider pass trunk collider - that’s my first idea, but what if hero is behind the tree, and monster is in front of the tree in same time?

Can anyone think of better idea? Is there any well known solution for this problem?

Thanks in advance for every reply.

Hi man, in this video of Unite 2014 www.youtube.com/watch?v=HM17mAmLd7k at ~33minutes Veli-Pekka show a script that may help you.
He changes the Order In Layer of the sprite at runtime based on the position of the object.

1 Like

Uhmm… why are you using layers and not just the z-axis?
You can write a tiny script that couples the y-position to the z-position like this:

Vector3 position = this.transform.position;
position.z = -position.y;

And to keep things from being all over the place in your 3D scene view, you can divide by some number so things stay relatively around the same z-position:

position.z = -position.y/1000

He is using the Ortographic Camera and the 2D system, so the z position isn’t used to calculate depth.

For me it is??? I am on the 4.6 beta, but I don’t think this is something new.
I just created a new 2D project and added 2 sprites, and it does use the z for depth.

What I did notice though is that the camera is pointing to the positive of the z-axis. So the minus that I gave in my example would need to go.

My bad… did some tests and looks like the z position can be used to order sprite renderer’s in the scene.
Back when 2D Components for Unity were released this could only be achieved with layer’s.

But my previous tip is still a good choice :slight_smile:

@Vitor_r
Ah, I just took a look at the video you posted. From your original post I thought you where talking about a script that would revolve around the layers. But yeah, renderer.sortingOrder looks way better.

@Vitor_r
Thanks! That’s exacly what I needed. I guess it won’t be so easy to implement in my game, but now when I am sure my idea was right I can start to code it.

@SpacemanBoots
Thanks for Idea, but I really want to avoid changing axis and work purely in ortographic mode.

Ofcourse if someone have better idea how to solve this problem without changing axis I would sincerely like to hear it.