1
\$\begingroup\$

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 A

Example B Map X = 4 Y = 3

Example B

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?

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Are you trying to obtain the x and y coordinate from a single value? Try this tileX = index % width; tileY = index / width; \$\endgroup\$
    – Mike Hunt
    Commented Mar 7, 2016 at 15:04

2 Answers 2

4
\$\begingroup\$

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();
  }
}
\$\endgroup\$
0
0
\$\begingroup\$

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;
}
\$\endgroup\$
1
  • \$\begingroup\$ Hmm.. what's the difference with what's in my answer? \$\endgroup\$
    – Vaillancourt
    Commented Mar 8, 2016 at 15:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .