我想从文本文件中加载游戏中的级别,并将其加载到2d数组中,这就是该级别文本文件的外观:
0,0,0,0,0,0,0,0,0,0
1,1,1,1,1,1,1,1,1,1
2,2,2,2,2,2,2,2,2,2
3,3,3,3,3,3,3,3,3,3
4,4,4,4,4,4,4,4,4,4
5,5,5,5,5,5,5,5,5,5
6,6,6,6,6,6,6,6,6,6
7,7,7,7,7,7,7,7,7,7
8,8,8,8,8,8,8,8,8,8
9,9,9,9,9,9,9,9,9,9我希望每个数字都是独立的,逗号将充当分隔符,但我不知道如何将这些数据实际地输入到2d数组中。这就是我有多远:
Tile[,] Tiles;
string[] mapData;
public void LoadMap(string path)
{
if (File.Exists(path))
{
mapData = File.ReadAllLines(path);
var width = mapData[0].Length;
var height = mapData.Length;
Tiles = new Tile[width, height];
using (StreamReader reader = new StreamReader(path))
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
Tiles[x, y] = new Tile(SpriteSheet, 5, 3, new Vector2(x * 64, y * 64));
}
}
}
}
}行Tilesx中的数字5和3,y= texture ()表示纹理在纹理图谱中的位置。我想要添加一个if语句,比如如果文件中的数字在topleft是0,我希望Tiles0,0设置为我的纹理图谱中的特定行和列。在这方面的任何帮助都是非常感谢的,我没有看到它!
发布于 2017-09-10 18:44:30
首先,var width = mapData[0].Length;将返回字符数组的长度,包括逗号,它是19。看起来,您不希望它返回逗号。因此,您应该像这样拆分字符串:
Tile[,] Tiles;
string[] mapData;
public void LoadMap(string path)
{
if (File.Exists(path))
{
mapData = File.ReadAllLines(path);
var width = mapData[0].Split(',').Length;
var height = mapData.Length;
Tiles = new Tile[width, height];
using (StreamReader reader = new StreamReader(path))
{
for (int y = 0; y < height; y++)
{
string[] charArray = mapData[y].Split(',');
for (int x = 0; x < charArray.Length; x++)
{
int value = int.Parse(charArray[x]);
...
Tiles[x, y] = new Tile(SpriteSheet, 5, 3, new Vector2(x * 64, y * 64));
}
}
}
}
}https://stackoverflow.com/questions/46144130
复制相似问题