217
« on: November 22, 2011, 03:05:06 pm »
So, lets put it into steps.
1) Load your image(s) containing the tiles. I suggest using one only image with all the tiles, and using the sprite to set the correct SubRect for each tile. That way, you will have an array of sprites, each representing one different kind of tile, and one image.
2) Create your map matrix. Usually, this is done using a matrix of numbers: each number representing one position of the sprites array. Lets supose that the tile on the second sprite of the array is on the second and third columns of the first line; The map matrix will have:
map[0][1] = 2;
map[0][2] = 2;
Remember that, as the positions start at 0, the second position is 1, and 2 is the third.
3) Loop though your map matrix, as you specified on your opening post, and print one sprite at each iteration. Don't forget to set the right position to the sprite before printing it, or else all of your sprites would be printed on the default position, one on top of the other.
3.1) To get the right sprite is easy:
If the number is zero, then we have no tile on the position... Nothing to be done. Any other positive number will give us the sprite by that formula:
sf::Sprite rightSprite = sprites[map[line][column] - 1];
We've put - 1 on the positions because they starts at 0 on the array, and on our map we consider them starting from 1.
3.2) To set the right position, we must know the size for each tile. The best way is to have tiles of the same size. Then, we can get the position with:
int xPosition = column * tileSize;
int yPosition = line * tileSize;
That way, if we are printing the first line (line = 0), its y position would be 0. If we are printing the second (line = 1), it y position is tilesize. And so on.
Then to put the position on the sprite:
sprite.SetX(xPosition);
sprite.SetY(yPosition);
I think that is more than enough for you to make a tile based map.