Pregunta

I'm struggling at converting mouse/screen coordinates to isometric tile index. I have tried about every formula I could find here or on internet but none of them seems to work or I am missing something.

enter image description here

Here is a picture, origin is in the top left corner and dimensions of one tile are 128x64px.

I would appreciate any help, thanks.

¿Fue útil?

Solución

Basically, you need to apply a rotation matrix with a few other bits. Here's some sample code written in AWK which should be easy to port to any other language:

END {
   PI = 3.1415;
   x = 878.0;
   y = 158.0;

   # Translate one origin to the other 
   x1 = x - 128*5;
   # Stretch the height so that it's the same as the width in the isometric
   # This makes the rotation easier
   # Invert the sign because y is upwards in math but downwards in graphics
   y1 = y * -2;

   # Apply a counter-clockwise rotation of 45 degrees
   xr = cos(PI/4)*x1 - sin(PI/4)*y1;
   yr = sin(PI/4)*x1 + cos(PI/4)*y1;

   # The side of each isometric tile (which is now a square after the stretch) 
   diag = 64 * sqrt(2);
   # Calculate which tile the coordinate belongs to
   x2 = int(xr / diag);
   # Don't forget to invert the sign again
   y2 = int(yr * -1 / diag);

   # See the final result
   print x2, y2;
}

I tested it with a few different coordinates and the results seem correct.

Otros consejos

I tried the solution by acfrancis and I found that the function has its limits when it comes to negative indices. Just in case someone else will tackle this issue: Reason for issue: negative values like -0.1.... will be cast to 0 instead of -1. Its the classic "there is only one zero" problem for arrays.

To solve it: before casting the x2, y2 values to int: check if xr/diag < 0 and, if true, result = result - 1 (respectively for y2: yr * -1 / diag < 0 then result = result -1) you then cast the result values to int like before.

Hope it helps.

Addition: The translation of the origin by 128*5 seems to specific to a certain case so i guess this should be removed in order to generalize the function.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top