# How to convert mouse coordinates to isometric indexes?

I draw isometric map with tile 64x32:

const Offset = 160;
int X, Y;

for (int a=0; a < 6; a++)
for (int b=0; b < 6; b++) {
X = a * 32 - b * 32 + Offset;
Y = a * 16 + b * 16;
DrawTile(X, Y, tile);
}


Image, illustrating this code: Dear professionals, please, help with a formula of transformation of mouse coordinates in isometric indexes of a cell. Example: (105; 100) -> [1; 4].

• possible duplicate of Isometric rendering and picking? Aug 22, 2012 at 6:39
• Side note: If you don't actually want to access the previous value of a variable you're incrementing, as in while(val = arr[i++]) or similar constructions, don't use it. Use ++aand ++b instead. Aug 22, 2012 at 7:18

You need to determine the transformation matrix from tile-space coordinates to screen-space coordinates, then calculate the inverse matrix for this, which when applied to screen-space coordinates transforms them to tile-space ones.

By the way: Your offset is actually pointing to a place which would be (0.0, 1.0) in any sane coordinate system, but that's not a big problem, just something to keep in mind. This means that the offset of the origin of your transformed coordinate system is at (Offset + 32, 0).

## Specific case

What you are basically doing for transforming tile-space (a, b) coordinates into screen-space (x, y) coordinates is to run it through the following transformation matrix: Definitions: a and b for the tile (0, 0) are in the range [0.0, 1.0) with (0.0, 0.0) being the upper corner, (1.0, 1.0) the lower corner, (0.0, 1.0) the left corner and (1.0, 0.0) the right corner in screen space.

We extend the coordinate definitions by a constant third coordinate (it's always exactly 1) to be able to incorporate the translation into the matrix.

Now you can create the inverse matrix for this transformation. The basic formula is: ... with C being the matrix of cofactors for A.

In your case, the determinant |A| is always 1024, no matter the offset, so the inverse matrix is: ## Example calculation

Now, for your example data ...

Put your number for offset in the formula, and you get: Multiplying (105, 100, 1) (the screen coordinates) with the matrix gets you:  Since the third coordinate is always 1, we don't have to calculate it. Round down to the nearest whole number, and you get (1, 4) as your tile space coordinates, as expected.

## General dimetric projection matrices

If you have a perspective like this with each tile being 2 w in width (64 in the example, so w = 32) and 2 h in height (32 in the example, so h = 16), and the offset of the origin point in screen space being fx and fy for the horizontal and vertical axis respectively (192 and 0 in the example), the matrices look like follows.

Tile space to screen space Screen space to tile space 