- Home /
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:
Answer by Nikaas · Dec 24, 2017 at 08:46 AM
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;
}
I have tried this and it doesn't work, since the grid is in the middle, if you just add half a tile then when the position is on the right side then it goes too far and ends up outside of the grid.
It's a good suggestion and might work in some circumstances but not in this case.
Then substract ins$$anonymous$$d. You still may end up needing to handle edge cases because even on you images one grid is with more positions than the other. You would have to choose if you want to ignore the first or last x/y (or correct the grid dimensions by one).
Answer by dracozinc · Jan 30 at 02:04 AM
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
Your answer
Follow this Question
Related Questions
Is there a way to check if something was snapped on a specific grid? 1 Answer
Create Grid and Snap Rigidbodies to Grid 1 Answer
How to drag gameobject (only x y) snapped to a grid? 2 Answers
Snapping to Grids 0 Answers
Grid snapping 0 Answers