Basic formula for calculating grid position:
- Take the world x and z location of the object you want snapped to the grid and divide by the number of “boxes” on that axis. So if we have a grid that is 32 tiles wide and 32 tiles tall, divide the x and z by 32. This will give you the grid location…ie this position is at grid point (2,2). It is a good idea to round the decimal using “floor” function.
float gridLocX = floor(x / 32.f);
float gridLocY = floor(y / 32.f);
NOTE: This formula expects the top right corner of the grid to to be located at 0,0. If this is not the case, the coordinates with have to be adjusted to take into account the position of the grid. Something like:
float gridLocX = floor((x - gridOriginX) / 32.f);
float gridLocY = floor((y - gridOriginY) / 32.f);
(Subtract if the grid origin is positive on the x/y axis, add if the x/y is negative on the axis)
- Multiply that by the size of the “tiles” in world space of each grid square. For example 20cm x 20cm grid size:
float gridWoldPosX = gridLocX * 20.f;
float gridWoldPosY = gridLocY * 20.f;
(Don’t forget to add the grid origin back into the gridWorldPos if the origin is not located at 0,0)
- After that, there is some basic math you can do to center it within the grid tile. Divide the width and depth of the object by 2 to get the half size, then add that to gridWorldPos
I explained it in code, but it should be simple to translate it to blueprints. I haven’t tested this in UE4 but the idea is universal. This method is good for if you don’t have grid tile objects and the grid is just empty space.
Alternatively, you could do something like cast a ray to find the tile object that that position and maybe parent the object to that grid (I’m not sure if this is possible in UE). Actually, you don’t even have to parent it, just set the object’s location to the tile location.