How do I generate a 2D tile map from an array like in this tutorial for XNA ? I basicly want to generate a static map based on my tile prefabs.
Answer
Its actually very similar to the way it is done in XNA , only a few changes in the syntax and loading approach.
Here is the most basic way in which it can be done. You can build on top of it as per your needs.
Before we start, we need to make some tile prefabs and store it inside the resources folder.
Lets define some variables, and initialise them some default values.
//Your Tile Map
public int[,] tileMap = new int[,]
{
{0,1,2},
{1,1,0},
{2,2,2}
};
public float TileSize;
public Vector2 StartPoint;//top left corner of the map
// Use this for initialization
void Start ()
{
TileSize = 1;
StartPoint = new Vector2 (1, 1);
PopulateTileMap ();
}
The StartPoint is the top left corner of the map. So you can define from where it should start populating on the screen.
Now lets look at the core logic behind populating the tiles , as per our tilemap.
public void PopulateTileMap ()
{
for(int i = 0 ; i < 3 ; i ++)
{
for(int j = 0 ; j < 3 ; j ++)
{
GameObject prefab = Resources.Load ("tile_"+tileMap[i,j].ToString()) as GameObject;
GameObject tile = Instantiate(prefab, Vector3.zero, Quaternion.identity ) as GameObject;
tile.transform.position = new Vector3(StartPoint.x + ( TileSize * i ) + ( TileSize/2) , StartPoint.y + (TileSize * j ) + ( TileSize/2), 0);
}
}
}
Here we instantiate the prefabs from our resources folder. The name is created as per the tile map we have defined earlier. For position, adding the tile size to the starting point will give the top left corner of the individual tile. But as our pivot is in centre we add an extra offset of (TileSize/2).
Hope this resolves your doubt :)
No comments:
Post a Comment