Monday, March 30, 2015

geometry - 2D isometric: screen to tile coordinates


I'm writing an isometric 2D game and I'm having difficulty figuring precisely on which tile the cursor is. Here's a drawing:




where xs and ys are screen coordinates (pixels), xt and yt are tile coordinates, W and H are tile width and tile height in pixels, respectively. My notation for coordinates is (y, x) which may be confusing, sorry about that.


The best I could figure out so far is this:


int xtemp = xs / (W / 2);
int ytemp = ys / (H / 2);
int xt = (xs - ys) / 2;
int yt = ytemp + xt;

This seems almost correct but is giving me a very imprecise result, making it hard to select certain tiles, or sometimes it selects a tile next to the one I'm trying to click on. I don't understand why and I'd like if someone could help me understand the logic behind this.


Thanks!




Answer



For accurate measure, we could consider following:


Lets first consider how to transform coordinates from isometric space, determined by i and j vectors (as in isometricMap[i,j]) or as the yt and xt on the screen, to screen space, determined by x and y of the screen. Lets assume your screen space is aligned at origin with isometric space for simplicity's sake.


One way to do the transform is to do a rotation first, then scale the y or x-axis. To get the necessary values to match your yt and xt I can't quite come up with on the spot here. You may create a matrix to do this or not and then use reverse matrix, but the reverse operation is basically what you want.


Scale the value in reverse and then rotate backwards to get the values and round downwards.


There are other ways to this I guess, but this seems most proper to me right now.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...