Draw textures in specific order

I guess this has to do with in between spriteBatch.Begin() and spriteBatch.End();

//regarding here(????)

I’m trying to draw textures in a certain order according to their Position.Y

For example:

if (kiwi.Position.Y < orange.Position.Y){
//i want kiwi to be behind orange
// and orange to be in front

But I wouldn’t know how to implement this at all.

Use SpriteSortMode.BackToFront or SpriteSortMode.FrontToBack in SpriteBatch.Begin() and pass your Y value as the layerDepth parameter in the Draw calls.

1 Like

Can you show me what to put in spriteBatch.Draw()? I tried it and now more than half of my sprites disappeared.

spriteBatch.Draw(Texture, Position, null, null, Vector2.Zero, 0f, new Vector2(1,1), Color.White, SpriteEffects.None,          Position.Y);

that’s what i put

        spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, Scale);
        spriteBatch.Draw(p1, position, null, Color.White, 0f, Vector2.Zero, new Vector2(1, 1), SpriteEffects.None, position.Y);
        spriteBatch.Draw(p2, position2, null, Color.White, 0f, Vector2.Zero, new Vector2(1, 1), SpriteEffects.None, position2.Y);

They both just vanish if there anywhere on the Y axis except 0.

I believe the layer property only takes a float from 0.0-1.0 so nothing will work besides 0 and possibly 1 in your case.

You will have to average out by your max Y size you expect, ie if you want to lay them by y out of 100.

``float layer = y / 100f

Now a sprite at y = 0 will be drawn at 0.0f, a sprite at y = 50 will be drawn at 0.5f and a sprite at y = 100 will be drawn at 1.0f.

Thanks! I made two float layers and wrote

layer = position.Y/1080f;

since the screen is 1080 pixels high and that’s all i need currently.

You could also check it against backbuffer height or the RT or viewport etc. to prevent changing your 1080f everytime.