0
votes

It may be a noob question but here it is...

I'm using Visual Studio with the XNA Framework (3.1) and I'm only going to draw 2D sprites for my game, here is the Draw Method in the main class:

GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);
            background.Draw(this.spriteBatch);
            player1.Draw(this.spriteBatch);
            player2.Draw(this.spriteBatch);
            spriteBatch.End();
            base.Draw(gameTime);

The problem is that the player2 is overlapping player1 (because he is drawn after), and I'd like the lowest one of the 2 players (by their position) to be drawn last (to simulate depth).

Thanks in advance! (and sorry for my Engrish, I'm French...)

3
I suppose that you're talking about the DepthBuffer? I don't really know how to use it, I added: spriteBatch.GraphicsDevice.RenderState.DepthBufferEnable = true; and it didn't change anything. I must be using it the wrong way...jobadluck

3 Answers

2
votes

There is an overload of the SpriteBatch.Draw method which offers a 'layerDepth' parameter (from 0 for front, to 1 for back). You can set an individual sprite's layerDepth and use spriteSortMode.BackToFront in the SpriteBatch.Begin method.

0
votes

Ok thanks to Steve I did it. I just changed my player SpriteBatch.Draw method to SpriteBatch.Draw(X,X,(...),layerDepth) with layerDepth getting updated with the Y position of the players. Had to use spriteSortMode.FrontToBack: everything was reversed because of the origin being in the upper-left corner. Thanks!

0
votes

Steve's Answer is probably easiest , but sometimes Immediate drawing is favorable. An alternative is sort your players and objects in a list based on their Y axis.