# Mouse position to grid position not working

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.

Did some testing and I think your only mistake is in adding the offsets rather than subtracting them. Other than that it's been working for me, although you could simplify those equations quite a bit to get rid of all those divisions.

While trying, I've written this example code on JSFiddle. I omitted drawing the grid, but you should see a moving "tile" when moving your cursor over the screen rectangle.

Here are my conversion functions:

From screen to grid:

var grid_x = Math.floor((screen_x - offset_x + 2 * (screen_y - offset_y)) / grid) + 2;
var grid_y = Math.floor((2 * (screen_y - offset_y) - (screen_x - offset_x)) / grid) + 1;


From grid to screen:

var tile_x = (grid_x - grid_y - 2) * grid / 2 + offset_x;
var tile_y = (grid_x + grid_y - 4) * grid / 4 + offset_y;


The actual offsets might need some adjustment, based on how you'd like to originate your tiles etc.

As a bonus, I've left your own screen to grid conversion in there, so just uncomment it to see it working (all I did was subtracting offsets rather than adding them up). Although keep in mind the offsets aren't 100% correct when using your formula in the example.