# Calculate Position on Tile Map by single Index

I stumble about a Math Problem for calculating a Position on a dynamic tile-map.

So i got a List of Tile Entities. Every Tile got his one unique Index Value and i have to set the parameters for Map Height and Width.

Example A Map X = 3 Y = 4

Example B Map X = 4 Y = 3

To get the X Position Value of Tile E6 i know i have to use Map.X % 6. But i'm not sure how to get the Y Position of the Tile by his Index. % in this case stands for the modulo operation (c#).

Is there a name for such an calculation? Does somebody already know the answer?

• Are you trying to obtain the x and y coordinate from a single value? Try this tileX = index % width; tileY = index / width; – Mike Hunt Mar 7 '16 at 15:04

How to get X and Y coordinates in a 2d array from a single index? You use the modulo (%) for the x coordinate and you use the integer division (/) for the y coordinate:

array< array< object, mCanvasWidth >, mCanvasHeight > mDirtMap;
int totalSize = mCanvasHeight * mCanvasWidth;

for ( int i = 0; i < totalSize; ++i )
{
int xIndex = i % mCanvasWidth;
int yIndex = i / mCanvasWidth;
mDirtMap[yIndex][xIndex].doWhateverToObject();
}


Alternatively, what if you're stuck with a one dimension array that represent 2-dimension data? Here is how to get the index based on a set of x, y coordinates:

array<object, mCanvasHeight * mCanvasWidth> mDirtMap;

for ( int y = 0; y < mCanvasHeight; ++y )
{
for ( int x = 0; x < mCanvasWidth; ++x )
{
int index = y * mCanvasWidth + x;
mDirtMap[index].doWhateverToObject();
}
}

• @Smartis No, you're not :P This happens to all of us once in a while :P – Alexandre Vaillancourt Mar 7 '16 at 15:02

How to get X and Y coordinates in a 2d array from a single index?

-You can use simple index with width & height. Here a example :

int width = 4;
int height = 3;

//E6 index = 6

public int getTileIndexFromArray(int x, int y)
{

for ( int y = 0; y < height; y++)
{
for ( int x = 0; x < width; x++ )
{
int index = x + y * w;

//For Example
Tile t = getTile(index);
if(t.Name != "E6") continue;

return tiles[index];
}
}
return tiles[0];
}

public Tile getTile(int x, int y) {
if (x < 0 || y < 0 || x >= width || y >= height) return Tile.air;
return Tile.tiles[tiles[x + y * width]];
}

public Tile getTile(int index) {
return Tile.tiles[tiles[index]];
}

public void setTile(int x, int y, Tile t) {
if (x < 0 || y < 0 || x >= width || y >= height) return;
tiles[x + y * width] = t.id;
}

• Hmm.. what's the difference with what's in my answer? – Alexandre Vaillancourt Mar 8 '16 at 15:44