我是Monogame和C#的新手。我正在尝试使用TiledSharp在屏幕上渲染测试图块地图。但是,当我尝试绘制多层时,它们显然是在循环并互相绘制。
这是我的绘制方法代码:
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
spriteBatch.Begin(sortMode: SpriteSortMode.FrontToBack, blendState: BlendState.AlphaBlend, samplerState: SamplerState.PointClamp, null, null, null,
Matrix.CreateScale(6.0f));
for (currentTileLayer=0; currentTileLayer < easyMap.TileLayers.Count; currentTileLayer++)
{
Console.WriteLine(easyMap.TileLayers[currentTileLayer].Name.ToString());
for (var i = 0; i < easyMap.TileLayers[currentTileLayer].Tiles.Count; i++)
{
int gid = easyMap.TileLayers[currentTileLayer].Tiles[i].Gid;
// empty tile, do nothing
// gid => global id of tile
if (gid == 0)
{
}
else
{
int tileFrame = gid - 1;
int column = tileFrame % tilesetTilesWide;
int row = (int)Math.Floor((double)tileFrame / (double)tilesetTilesWide);
float x = (i % easyMap.Width) * easyMap.TileWidth;
float y = (float)Math.Floor(i / (double)easyMap.Width) * easyMap.TileHeight;
Rectangle tileSetRec = new Rectangle(tileWidth * column, tileHeight * row, tileWidth, tileHeight);
spriteBatch.Draw(easyTileset, new Rectangle((int)x, (int)y, tileWidth, tileHeight), tileSetRec, Color.White);
}
}
}
spriteBatch.End();
base.Draw(gameTime);
}
我的原始地图看起来像这样:
当我运行代码时,它看起来像这样:
地图共有三层。如何修复循环?谢谢!
我可能错了,但我认为您需要从头到尾对瓷砖进行排序。应该先渲染位于底部的任何瓷砖。
在for (currentTileLayer=0; currentTileLayer < easyMap.TileLayers.Count; currentTileLayer++)
中
用var orderedTiles = easyMap.TileLayers.OrderBy(t => t.Tile.Gid)
替换您的TileLayers
您应该使用排序的图层,因为Tiled很好地支持它们。使用图层可为您提供更多的地图设计可能性。我还可以使您的角色隐藏在对象等后面。在平铺中,如果需要在顶部几层,请先创建背景层,以避免错误的绘制顺序。
一个简单的解决方案可能看起来像这样
const int LAYER_BACKGROUNDLAYER = 0;
const int LAYER_FRONTLAYER = 1;
const int LAYER_TOPLAYER = 2;
取决于要使用的层数。
然后,您只需将要绘制的层号传递给Draw-Method。通常从0到最大数。
public void DrawLayer(int layer)
{
for (var j = 0; j < curMap.Layers[layer].Tiles.Count; j++)
{
int gid = curMap.Layers[layer].Tiles[j].Gid;
if (gid == 0)
{
//empty tile
}
else
{
//draw your tile
}
}
}
在这种情况下,“ curMap”是您当前的.tmx文件,它是通过curMap = new TmxMap(mapSource);加载的上面的绘制代码应该适合您的代码,因为我也基于TiledSharp示例;)