I have a function isoToScreen(x, y)
that converts Isometric coordinates to Screen coordinates.
var tileW = 16;
var tileH = 16;
var isoToScreen = function(x, y) {
var posX = (x - y) * tileW;
var posY = (x + y) * tileH / 2;
return [posX, posY];
};
But how would I make a function that converts screen coordinates back to Isometric coordinates?
var pos = screenToIso(16, 8);
pos[0] = 1; // Iso X
pos[1] = 0; // Iso Y
Answer
var screenToIso = function(screenX, screenY)
{
var isoX = screenY / tileH + screenX / (2*tileW)
var isoY = screenY / tileH - screenX / (2*tileW)
return [isoX, isoY];
}
To get this function you need to rewrite the original math
screenX = (isoX - isoY) * tileW
screenY = (isoX + isoY) * tileH / 2
Starting with the first line you get the following:
screenX = (isoX - isoY) * tileW
screenX / tileW = isoX - isoY
screenX / tileW + isoY = isoX
The second line:
screenY = (isoX + isoY) * tileH / 2
2*screenY = (isoX + isoY) * tileH
2*screenY / tileH = isoX + isoY
2*screenY / tileH - isoX = isoY
Now the two lines look as follows:
A) isoX = screenX / tileW + isoY
B) isoY = 2*screenY / tileH - isoX
Then substitute isoY in the line A, with the formula derived from line B:
isoX = screenX / tileW + 2*screenY/tileH - isoX
isoX+isoX = screenX / tileW + 2*screenY/tileH
2*isoX = screenX / tileW + 2*screenY/tileH
isoX = screenX / (2*tileW) + screenY/tileH
isoX = screenY/tileH + screenX / (2*tileW)
And finally, substitute isoX in line B, with the formula derived from line A:
isoY = 2*screenY / tileH - screenX / tileW - isoY
2*isoY = 2*screenY / tileH - screenX / tileW
isoY = screenY / tileH - screenX / (2*tileW)
Solving linear equations comes very much in handy for a lot of programming, especially graphics or game related programming. Pick up a book on Algebra or read some online tutorials, you will thank yourself later.
No comments:
Post a Comment