Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 10 down vote accepted

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.

share|improve this answer
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

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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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