Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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

2 Answers 2

up vote 4 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
1  
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
4  
Can you explain what you mean by "the right feel"? And why the ceiling function does that? –  Byte56 Apr 13 at 1:01

Your Answer

 
discard

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.