# Snap object to grid with offset?

I’m trying to make sure that an object snaps to a grid, but I want it to be in the center of the grid squares instead of the intersection between the grid lines.

Here’s a method that returns a position but snapped to a grid size of 2 so for instance the x values that could be returned are -4, -2, 0, 2, 4, 6…

``````Vector2 SnapToGrid (Vector2 pos)
{
Vector2 gridPos = pos;
gridPos.x = Mathf.Round (pos.x / gridSize.x) * gridSize.x;
gridPos.y = Mathf.Round (pos.y / gridSize.y) * gridSize.y;

return gridPos;
}
``````

but I need a method that would instead return x values of -5, -3, -1, 1, 3, 5… so on an offset.

Here’s an image to help show what I mean:

You can just add/subtract half a “tile” after you do the rounding that calculates the grid position.

`````` Vector2 SnapToGrid (Vector2 pos)
{
Vector2 gridPos = pos;
gridPos.x = Mathf.Round (pos.x / gridSize.x) * gridSize.x + gridSize.x / 2f;
gridPos.y = Mathf.Round (pos.y / gridSize.y) * gridSize.y + gridSize.y / 2f;

return gridPos;
}
``````

Vector2 SnapToGrid (Vector2 pos)
{
int offset = -1;
Vector2 gridPos = pos;
gridPos.x = Mathf.Round ((pos.x - offset) / gridSize.x) * gridSize.x + offset;
gridPos.y = Mathf.Round ((pos.y - offset) / gridSize.y) * gridSize.y + offset;

``````        return gridPos;
}
``````

here is another solution