Monogame C# - How do I draw my sprites between tilemap layer 0 and 1?

490 Views Asked by At

I have a tilemap:

this.TileMap = Content.Load<TiledMap>("Maps/MyTileMap");
_tiledMapRenderer = new TiledMapRenderer(GraphicsDevice, this.TileMap);

I would like to render my normal sprites between layer 0 and 1. Kinda like this:

DrawLayer(0, 0f);
foreach(var sprite in this.Sprites)
{
    sprite.Draw(spriteBatch, gameTime);
}
DrawLayer(1, 1f);

sprite.Draw does:

var destRectangle = new Rectangle((int)Position.X, (int)Position.Y, Texture.Width, Texture.Height);
spriteBatch.Draw(Texture, destRectangle, null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 0.2f);

And DrawLayer does:

var layer = this.TileMap.Layers[idx];
_tiledMapRenderer.Draw(layer, this.Camera.GetViewMatrix(), depth: depth);

But my regular sprites are still on top of everything.

enter image description here

The terrain is layer 0, the tree is on layer 1 (obviously).

I would think providing layerDepth should assure the correct draw order, but clearly it doesn't.

Any pointers on how to fix this?

Or, alternatively,

how can I add my sprites to a layer? 

I heard that's an option, but I never found out how.

2

There are 2 best solutions below

0
Spikee On BEST ANSWER

As expected / hoped, it had to be something simple because I can't believe everyone would use Tiled, if it doesn't actually produce a workable result.

So what worked is adding this to the .Begin():

_spriteBatch.Begin(sortMode: SpriteSortMode.ImmediatetransformMatrix: this.Camera.GetViewMatrix(), );

That gets me this:

enter image description here

6
Blindy On

That's not going to work, because you don't know what layers to assign to that tree relative to your person sprite. Specifically, if the person is south of the tree, you want it to draw on top of the tree, while when it's north of the tree, you want it to be under the tree.

You will instead have to sort your sprites so that they're draw from the bottom of the screen up.