Generate Tile Map from array

QuackTheDuck picture QuackTheDuck · Oct 8, 2013 · Viewed 13.1k times · Source

I've been thinking about trying to create a RPG game, a simple game with movement, pick up items, and open doors.

I've been thinking for a long time about the tile map engine, but i can't find anything that works :/

Basically what i'm trying to accomplish is i have an enum, like:

public enum tileSort { Dirt, Grass, Stone, Empty }

And when the engine runs through the array, which will have 0's, 1's, etc, I'm thinking about a switch statement, something like:

switch(tileSort) 
{ 
    case '0':  tileList.Add(Content.Load<Texture2D>("Tiles/grass")) 
}

The problem is that I have no idea on how to make this possible, all that I've been able to create is an engine that runs through and generates depending on which content you load first into the game.

I know this is confusing, as I'm not good at explaining myself.

Thanks in advance.

Answer

roim picture roim · Oct 8, 2013

You can use some tools to help you:

I'm sure you can find many others.

About the snippets of code you wrote, you don't want to call

Content.Load<Texture2D>("Tiles/grass")

multiple times for a single texture. Load each texture only once and print the same resource multiple times. You could have something like this:

var tileList = new List<Texture2D>();
string[] tiles = { "dirt", "grass", "stone", "empty" };

foreach (var s in tiles) {
    tileList.Add(Content.Load<Texture2D>("Tiles/" + s));
}

Now each texture is loaded only once, and you can access it using tileList[index].

The next step is to print the tiles on the screen. I'll assume you have loaded your tiles into a 2 dimensional array with the tile indexes.

int[,] tileMap = {{1, 2, 0}, {0, 1, 2}, {3, 3, 1},};

for (int i = 0; i < 3; ++i)
    for (int j = 0; j < 3; ++j)
        spriteBatch.Draw(tileList[tileMap[i, j]], new Vector2D(50*i, 50*j), Color.White);
        // Assuming the tiles are 50x50 pixels

This tutorial teaches what you want with more details: http://www.xnaresources.com/?page=Tutorial:TileEngineSeries:1