Totally lost trying to render a 2D tile-based map

Started by
1 comment, last by KevinChuca 10 years, 4 months ago

Hello guys, I've been reading a lot about 2D how to render tile-based maps.

The thing is, the more I read, the more confused I am, so I deceided to create my own logic.


// map widht
int w = 100;
// map height
int h = 100;
// the 2nd dimension is like this
// {tile_x,tile_y,tile_graphic}
int tiles[][3];

for(i=0;i<w*h;i++)
{
   // rendering routine here
}

I know this is very basic sftuff but do you think I can start from here?

Or maybe I should use a different approach?

Thanks in advance.

Advertisement

I might suggest you creating a struct that represents tile like this:


struct Tile
{
    int x;
    int y;
    int graphic;
};

Then you could do something like this:


int w = 100;
int h = 100;

Tile * tiles = new Tile[w*h]; // allocate memory for new array of tiles with size of map

// iterate through tiles
for(int i = 0; i < w*h; i++)
{
    Tile & tile = tiles[i];

    // here you can do whatever you want with your tile.
    // for example renderTile(tile.graphic, tile.x, tile.y);
}

There are many ways to implement this. You could also use std::vector instead of array for storing tiles, because it would be much easier to add and remove tiles dinamicaly.

Also you might not want to store tiles position in struct, instead you could use 2d array, like you tried to do before, then it would look something like this:


int w = 100;
int h = 100;

int ** tiles = new int[w][h]; // allocate memory for new array of tile graphics with size of map

// iterate through tiles
for(int y = 0; y < h; y++){
    for(int x = 0; x < w; x++){
        int tileX = x*32;  // 32 would be the space bettwen tiles on x axis
        int tileY = y*32;  // same thing for y axis
        int graphic = tiles[x][y];

        // for example renderTile(graphic, tileX, tileY);
        // do whatever you want with this tile
       
    }
}

Also, we would probably want to store not only graphic in our array, but also other data, like if its collidable or not and other stuff. In that case, we would just replace "int ** tileGraphics = new int[w][h];" to "Tile ** tileGraphics = new Tile[w][h];"

As I said, there are many ways you could implement this, it's up to you what suits you best.

“There are thousands and thousands of people out there leading lives of quiet, screaming desperation, where they work long, hard hours at jobs they hate to enable them to buy things they don't need to impress people they don't like.”? Nigel Marsh

Thank you, that helped a lot.

This topic is closed to new replies.

Advertisement