I’ve been working on a tile based map engine for my game project in Xna C#. The system, like most others, uses a digit corresponding to a tile in a tileset mapped to a specific position on screen. This works fine, but requires every cell on screen to have a number manually entered. Instead, I’ve decided to have level layouts read from a .txt containing the number of each tile in the position it would be ingame, like so:
1111
0110
1001
1100
Where 1 is grass and 0 is dirt. Again, I’m aware this is a common technique. The code I have written can read each line and set the next position in the first column to the corresponding tile graphic. This is fine, but it does not help with the rest of the map. I’ve been searching and cannot find how you would split each number in a row into a separate number, so that the first line would read (0,0) = 1, (0,1) = 1, etc, so I can then match the coordinates to the x and y position on the map, and the value to the type of tile.
So what I need is the ability to assign a 2d array corresponding to the current position (how many characters left in the file, how many lines down in the .txt file), so I can just run two branched for loops (x and y) for every tile in the level ie:
for (x=0; x<levelwidth; x++)
{
for (y=0; y<levelheight; y++)
{
Row[x].Column[y].Tile = Convert.ToInt32(filepos[x,y]);
}
}
You don’t want to use 2D arrays because of heavy performance issues.
Also, you probably want to use a separator between tile numbers, like this
for two reasons; 1 you can use more than 10 different tiles, and 2 you can then use String.Split() and Int.Parse() in order to get your tile IDs and build your map.
In order to use a 1D array, instead of doing myMap[x][y], you do myMap[y*mapWidth+x].