Monday, November 12, 2012

Isometric Screen To World Coordinates

I struggled with this topic for a few days, to the point where I think I lost a few brain cells. When using a square grid it's very easy to click a mouse and know exactly where you are in your game world and which tile you clicked on. However, the math and dynamics change when it's an isometric grid and a grid tile is a 2:1 ratio, ie it's 128 pixels wide and 64 pixels high.

See the graphic below for an example.


Notice the blue square that is selected. Wrote some fairly involved code several different ways and just couldn't get this right. When I clicked near the middle of the tile I knew exactly which X and Y tile had been clicked, my code worked fine. However, when I clicked in the corner the problem became clear because my  logic thought I had clicked in the next tile over. I looked at this 10 different ways and just couldn't get my head around it. How?

Then I found this article while searching for an answer and it became clear. If you scroll down the page you will see the author talk about a rectangle graphic that's 5 colors. It took me a little bit but I understood the logic behind it. In Blitzmax this was fairly easy to do. When I clicked with the mouse I calculated which of these rectangles I was clicking on (I didn't actually display the graphic). Once there I calculated where in the actual rectangle I was clicking on and then pulled the color out. If it was white, I was clicking on whatever row I had coded in the grid. However, if the color was red or green, I knew I had to subtract the row. It worked great and now my world selection worked 100%. Phew!

No comments:

Post a Comment