Snap to center of grid - rounding

Hello,

So this is sort of going off the comment to an earlier post of mine (https://answers.unity.com/questions/1646112/how-to-snap-to-grid-cells.html), where I learned that I could get the center of a 2D collider. I’m relatively new to C# so please don’t judge me if my coding logic is bad.

I was thinking that I could get the current mouse position that would be passed in as a parameter to a certain method. This method would take that parameter and round it to the center coordinates of the nearest 2D collider. My goal is to be able to click on a sprite, and then click on another point on this coordinate grid, and have the sprite snap to the center of the grid. However, like I mentioned in the earlier post, I can’t use Mathf to round to whole numbers because none of my numbers divide evenly.

Any thoughts on how I can achieve this exactly though code, or any other methods to doing this would be really appreciated!

Thanks!

Convert your world position to a grid position by dividing by your grid dimensions, casting the result to an integer, and then multiply that by your dimensions and add the offset to get to the final, snapped position.

pseudocode:

int gridX = position.x / grid width (3.1?);
int gridY = position.y / grid height (2.2?);

float snappedX = gridX * grid width + offset (half your grid width?)
float snappedY = gridY * grid height + offset (half your grid height?)
1 Like