function - Convert grid coordinates to world and back -


i have 2d grid tiles , place them in game world this: enter image description here

public static vector2 indextoworldposition(int mapx, int mapy, float tilewidth, float tileheight) {     float x = (mapx - mapy) * tilewidth / 2f;     float y = (mapx + mapy) * tileheight / 2f;     return new vector2(x, y); } 

tile width , height 1 , 0.5 world units. layout works expected , gives me typical diamond shape. want reverse function , correct map indices world position (e.g. mouse converted world space).

public static intvector2 worldpositiontoindex(vector2 mouseworld, float tilewidth, float tileheight) {     float x = mouseworld.x / tilewidth + mouseworld.y / tileheight;     float y = mouseworld.y / tileheight - mouseworld.x / tilewidth;     return new intvector2(mathf.floortoint(x), mathf.floortoint(y)); } 

the second function appears wrong. when testing, world positions close grid origin report correct indices, further away gets increasingly inaccurate, can't seem find out problem is. i've tried replace floortoint ceil , round, increased or decreased incorrect offset. also, have made sure reported world mouse position correct. i've written unit tests fixed input , expected output values, , reports, second function in fact not inverse first 1 correctly.

can spot mistake or point me in right direction how correctly invert first function?

addition: here unit tests both functions:

[testcase(0, 0, 0, 0)] [testcase(0, 1, -0.5f, -0.25f)] [testcase(0, 2, -1f, -0.5f)] [testcase(1, 0, 0.5f, -0.25f)] [testcase(1, 1, 0f, -0.5f)] [testcase(1, 2, -0.5f, -0.75f)] [testcase(2, 0, 1f, -0.5f)] [testcase(2, 1, 0.5f, -0.75f)] [testcase(2, 2, 0f, -1f)] public void conversion_works(int mapx, int mapy, float expectedx, float expectedy) {     unityengine.vector2 result = dimetriclayout.coordinatetoworldposition(mapx, mapy, 1f, 0.5f);     assert.areequal(expectedx, result.x);     assert.areequal(expectedy, result.y); }  [testcase(0, 0, 0, 0)] [testcase(0, 1, -0.5f, -0.25f)] [testcase(0, 2, -1f, -0.5f)] [testcase(1, 0, 0.5f, -0.25f)] [testcase(1, 1, 0f, -0.5f)] [testcase(1, 2, -0.5f, -0.75f)] [testcase(2, 0, 1f, -0.5f)] [testcase(2, 1, 0.5f, -0.75f)] [testcase(2, 2, 0f, -1f)] public void conversion_mouse(int expectedx, int expectedy, float mousex, float mousey) {     intvector2 result = dimetriclayout.worldpositiontocoordinate(new unityengine.vector2(mousex, mousey), 1f, 0.5f);     assert.areequal(expectedx, result.x);     assert.areequal(expectedy, result.y); }