如何使用文本文件中的矩阵在xna 4中制作地图

时间:2013-02-12 22:50:45

标签: map matrix xna 2d tile

我试图通过逐行读取文本文件来制作地图(因为我无法找到如何逐字逐句地完成)。所以我制作一个看起来像" 33000000111"的map00.txt; (每个数字都是一行,前两行是列数和行数,所以我加载它的矩阵看起来像 000 000 111 )。现在我应该在底部绘制3个瓷砖(1 =绘制瓷砖)。我是通过在矩阵*窗口高度(宽度)/矩阵行数(列)中的位置绘制平铺来实现的。 问题:我无法获得当前窗口宽度和高度的正确参数。

加载图块的代码:

    public int[,] LoadMatrix(string path) 
    {
        StreamReader sr = new StreamReader(path);
        int[,] a = new int[int.Parse(sr.ReadLine().ToString()), 
                           int.Parse(sr.ReadLine().ToString())];

        for(int i = 0; i < a.GetLength(0); i++)
            for (int j = 0; j < a.GetLength(1); j++)
            { a[i, j] =int.Parse(sr.ReadLine().ToString()); }

        sr.Close();
        return a;
    }

绘制图块的代码:

    public void DrawTiles(SpriteBatch sp, GraphicsDeviceManager gdm)
    {
        for(int i = 0; i < matrix.GetLength(0); i++)
            for(int j = 0; j < matrix.GetLength(1); j++)
            {
                if (i == 1)
                {
                    sp.Draw(tile, 
                            new Rectangle(j * (gdm.PreferredBackBufferWidth / 3),//matrix.GetLength(1),
                                          i * (gdm.PreferredBackBufferWidth / 3),//matrix.GetLength(0),
                                          gdm.PreferredBackBufferWidth / matrix.GetLength(1),
                                          gdm.PreferredBackBufferHeight / matrix.GetLength(0)),
                            Color.White);
                }
            }
    }

但结果是它们被绘制在屏幕底部上方约40个像素处!

我尝试使用GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height(宽度),但我得到了相同的结果。当我把计算出的数字(理论上)应该是宽度/列和高度/行时,我得到了我想要的东西。所以任何建议都会非常苛刻,因为我在google和Stack Overflow上长期坚持这一点。

1 个答案:

答案 0 :(得分:0)

以下是Draw代码的重写版本,应该可以使用:

public void DrawTiles(SpriteBatch sp, GraphicsDeviceManager gdm)
{ 
    //You would typically pre-compute these in a load function
    int tileWidth = gdm.PreferredBackBufferWidth / matrix.GetLength(0);
    int tileHeight = gdm.PreferredBackBufferWidth / matrix.GetLength(1);

    //Loop through all tiles
    for(int i = 0; i < matrix.GetLength(0); i++)
    {
        for(int j = 0; j < matrix.GetLength(1); j++)
        {
            //If tile value is not 0
            if (matrix[i,j] != 0)
            {
                 sp.Draw(tile, new Rectangle(i * tileWidth, j * tileHeight, tileWidth, tileHeight), Color.White);
            }
        }
  }
}