Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I get the position of tile 14 (or any other) when only knowing the following:
Tile ID: 14
Rows: 4
Columns: 7

The end result should be 2x4.

share|improve this question
Do consider waiting a while before accepting an answer, as there might appear a more correct and elaborated one. I'm not bitter, but I'm disappointed. – Lars Viklund Jul 28 '12 at 19:02
Actually yes, Lars' answer was better :) – Mikael Högström Jul 30 '12 at 12:02
up vote 3 down vote accepted
Column = TileID mod Rows
Row = TileID div Rows

so in most programming languages your example would be:

col = 14 % 4;
row = 14 / 4;
share|improve this answer

Such a bijective mapping is much easier to express if your tile indices and rows/columns are zero-based.

col: 0  1  2  3
  [  0  1  2  3  // row 0
     4  5  6  7  // row 1
     8  9 10 11  // row 2
    12 13 14 15  // row 3

If you look at the column numbers, as the column number increases by one, so does the tile index. More particularly, there's a pattern that for each row, it starts on a multiple of the row width, and increases by one.

This means that if we could get rid of that term, we would have our column number.

The modulus operator (commonly % in most languages) will take a number in a range [0,n) and map it to the values 0 through n-1, wrapping around.

That is, 7 % 4 == 3, 8 % 4 == 0, and so on.

A suitable expression for the column index is thus col = idx % width.

For the row, we need an expression that results in the same value for all values in the row. An operation related to modulus is division, so it's likely useful.

8/4 = 2, 9/4 = 2.25, 10/4 = 2.50, 11/4 = 2.75, which is almost what we want. We can feed the result of that into the floor() operation, which truncates away the fractional part of a floating point result, or in the case of integer division, it's already done for you.

So in summary:

zero_based_col =       zero_based_idx % row_width
zero_based_row = floor(zero_based_idx / row_width)
share|improve this answer
Ahh right you are, didn't see it wasn't zero based :) – Mikael Högström Jul 28 '12 at 18:18

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.