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?


3 Answers 3


You can do something like this

int gridCubeWidth = 16, gridCubeHeight = 16;

cube.Position.X = Math.round(cube.Position.X / gridCubeWidth) * gridCubeWidth;
cube.Position.Y = Math.round(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.

  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – numan
    Commented Jan 27, 2013 at 22:25

In my quick research, when you are snapping some geometry onto a grid:

  • As long as all the vertices of your polygon (in its final position) coincide with vertices of the grid (in other words, if what you're trying to snap fits nicely in the grid), then

  • You can snap any of the vertices of your polygon to its nearest grid vertex, and apply the same translation to all the others. You will always end up with the same resulting position.

This means you can simply pick a vertex and round its coordinates, or, if you're using a grid with side larger than one unit, use Austin's expression:

cube.Position.XorYorZ = Math.round(cube.Position.XorYorZ / gridCubeWidth) * gridCubeWidth;


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

  • 5
    \$\begingroup\$ Can you explain what you mean by "the right feel"? And why the ceiling function does that? \$\endgroup\$
    – House
    Commented Apr 13, 2014 at 1:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .