I have a function which converts my mouse position to grid position in the game but it is not working properly... its slightly off.
I have two functions - one which converts from grid to screen position (this particular one, works fine) and the code is:
function mapToScreen(gridX,gridY,screen) {
var grid = 64;
var x = (gridX - gridY) * (grid/2);
x -= screen.offsetX; //camera scroll offset X axis
x -= grid/2; //centre of the iso tile on X axis
var y = (gridX + gridY) * (grid/4);
y -= screen.offsetY; //camera scroll offset Y axis
y -= grid/4; //centre of the iso tile on Y axis
return [x,y];
}
So my function to do the opposite looks like this:
function screenToMap(pixelX,pixelY,screen) {
var grid = 64;
pixelX += screen.offsetX;
pixelX += grid/2;
pixelY += screen.offsetY;
pixelY += grid/4;
var gridX = Math.floor((pixelX / (grid/2) + pixelY / (grid/4)) /2);
var gridY = Math.floor((pixelY / (grid/4) -(pixelX / (grid/2))) /2);
return [gridX, gridY];
}
The problem is as shown below in the image, it doesn't return the correct number. The first corner tile should be [0,0]
.
Also notice the co-ordinate doesn't change correctly with the tile border. I don't know how to solve that either.