8
\$\begingroup\$

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?

\$\endgroup\$
11
\$\begingroup\$

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.

\$\endgroup\$
  • 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 Jan 27 '13 at 22:25
0
\$\begingroup\$

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;

\$\endgroup\$
-4
\$\begingroup\$

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.