Generate Tile Map from array

人盡茶涼 提交于 2019-12-05 21:57:09

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

To draw the tile map use this pseudo code

mapPlaceX = 0;
mapPlaceY = 0;

for (var y=0; y<TILEMAP_ARRAY.length; y++) {    

    mapPlaceX = 0;
    if (y != 0) { mapPlaceY += 30; }

        for (var x=0; x<TILEMAP_ARRAY[y].length; x++) {

                if (TILEMAP_ARRAY[y][x] == '0') { 
                    // draw image here  
                }           
                mapPlaceX += 30;

        }       
}

This goes through the whole array and draws a certain image if the array X and Y equal "0".

For collisions, use this:

var desiredX = playerX + pAngx;
var desiredY = playerX + pAngy; 

var indX = desiredX / 30;
var indY = desiredY / 30;

var cell = TILEMAP_ARRAY[indY][indX];

if (cell == 0) {
    // collision so don't move

}
else {
    // move

}

This finds the cell in the array that you are going to move to and moves if it is not equal to 0.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!