Background Objects Over Foreground Objects 2D

Hi there,

I’m really confused about how the layering of objects takes place. It doesn’t seem to make a lot of sense, given the furthest object back is at 0 and I need to increment in negatives to get closer to the camera. Also, pieces outside of grouped objects have their own sequencing system. I also feel like I’ve renumbered the Z-Axis several times and it doesn’t seem to keep.

I decided to create my own background for the Block Breaker video with PNG elements. They are all stored in a game object entitled Background. All the background objects are seemingly set properly on the Z axis - furthest back is 0 up to -5. See the image above - the sky is set to 0, stars -1, moon -2, horizon elements at -3 and -4, the purple fill and clouds at -4.5, and the grass at -5. The paddle is at -0.3 and the ball at -1.

The ball is separate from the background objects and is at -1… which puts it in front of all of the background objects. I don’t understand why the ball at -1 is in front of the background objects when -1, according to the background hierarchy, is close to the back.

Also, the ball sporadically goes behind the grass elements even though it’s positioned closest to the camera. See the gif below.

Any help would be great. Thank you!

1 Like

Hi @rLee,

When two sprites share the same position, the renderer does not know what to render first and renders the sprites in a random order. This can result in problems such as “disappearing” sprites. The effect is called z-fighting effect.

We give the sprites, or, to be more precise: the game objects, different z-position so the renderer always knows in which order it is supposed to render the sprites.

Did this help?


See also:

1 Like

Hi Nina, thanks for the reply,

The concept I understand - if the objects are on the same plane, so to speak, the program doesn’t know which one to render. However, the elements are set to different levels in this instance. The ball is pulled quite away from the grass elements and seems to be the on the top layer/plane/Z-Axis coordinate with every other element beneath it. That’s why I can’t figure out why the ball keeps going behind them - if I’ve set the Z-Axis to each layer of grass to -5. Even when I put the ball in the Background game object and set it to -6, it still goes behind the grass.

Oh, I see. Thanks for elaborating a bit further on the problem. What z-position has got your ball and what z-position has got your camera?

From what I read, your ball is at z = -1. Add a Debug.Log method call to the Update method in the Ball class. The condition should be: transform.position.z != -1. Log a message into your console along with the z-position if the condition gets evaluated to true. Maybe the ball changes its z-position during runtime.

This topic was automatically closed after 22 hours. New replies are no longer allowed.

Privacy & Terms