0

我是 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);

    }

我的原始地图如下所示:

在此处输入图像描述

当我运行代码时,它看起来像这样:

在此处输入图像描述

地图分为三层。我怎样才能修复我的循环?谢谢!

4

2 回答 2

1

我可能错了,但我认为您需要从后到前对瓷砖进行分类。无论哪个瓷砖应该在底部,都应该首先渲染。

for (currentTileLayer=0; currentTileLayer < easyMap.TileLayers.Count; currentTileLayer++)

将您的 TileLayers 替换为var orderedTiles = easyMap.TileLayers.OrderBy(t => t.Tile.Gid)

于 2019-12-12T17:13:45.297 回答
1

您应该使用已排序的图层,因为 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”是您当前通过curMap = new TmxMap(mapSource);加载的 .tmx 文件。 上面的绘制代码应该适合您的代码,因为我也是基于 TiledSharp 示例的;)

于 2019-12-13T11:32:04.760 回答