So I have an isometric map (but it could just as well be a 2D map) and an int[] array to store all of the block IDs on that map.
The array looks something like this (for a 4 by 4 block map):
0 0 1 0 0 2 0 1 0 2 1 0 1 0 3 2
That would translate into this on the map (first square):
0 0 1 0 0 0 1 0
0 2 0 1 0 2 X 1
0 2 1 0 0 2 1 0
1 0 3 2 1 0 3 2
There is an X on the second square.
How could I calculate X's position in the array? I tried doing basic multiplication: index = fieldWidth + fieldHeight
but I can't get it to work.
Also, how could I calculate X's coordinates using it's position in the array?
This is probably useful to anyone making 2D/isometric games.
When Position is zero-based (= starts with 0):
index = horizontalPos + verticalPos * 4
If it starts with 1 use:
index = horizontalPos - 1 + (verticalPos - 1) * 4
Get the zero-based Positions of X with index i in the linear array:
verticalPos = parseInt(i / 4); horizontalPos = i % 4;
EDIT:
To make it universally usable replace 4 with number of columns of your map.