# How can I snap a game object's position to a grid?

I'm making a game that involves "falling block" gameplay elements. The problem is, I'm not quite sure how to make it so that the blocks will snap to some kind of grid, in other words, I'm not sure how it will pick the closest cell to its position.

The blocks are not continuously snapping to a grid (i.e. they are subject to gravity). Any tips?

-

You can do something like this

``````int gridCubeWidth = 16, gridCubeHeight = 16;

cube.Position.X = Math.Floor(cube.Position.X / gridCubeWidth) * gridCubeWidth;
cube.Position.Y = Math.Floor(cube.Position.Y / gridCubeHeight) * gridCubeHeight;
``````

This basically rounds the X and Y positions to the nearest multiple of the cube dimensions. Then scales it by the cube dimensions to get the uniform position.

-
Wonderful! Thanks! – JesseTG Jul 28 '12 at 4:08
i think Math.round makes more sense. e.g imagine cubeWidth/height = 3. then a x=4 should map to 3 but x=5 should map to 6. – numan Jan 27 '13 at 22:25

Math.ceil gives the right feel to snap the blocks to right grids

-
Can you explain what you mean by "the right feel"? And why the ceiling function does that? – Byte56 Apr 13 '14 at 1:01