# Finding the closest point in a 1d grid.

This topic is 4327 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello. Im trying to code "snapping" for my level editor. That means that if you hold down a button while translating objects in space. The object will "snap" to the closest grid-node. I thought the algorithm for calculation the closest grid node would be easy to figure out. But i can't for my life get it right! If anyone know how to calculate the closest grid-node to a free moving object in one dimension, please tell me how. A function that "almost" works is:
	float get_closest_snap_pos(float pos, float step_size)
{
float mod = std::fmod(pos, step_size);
float closest_snap_pos = pos-mod;
return closest_snap_pos;
}


Im only using one dimension since i translate x,y,z separatly. The "step_size" variable is the size of one "step" in the grid. Ie the distance between a snapping point and the next in the grid. And "pos" is the position of the object. This works only if the position of the object is greater than then closest node, and greater than zero. Or less then the closest node, and less then zero. For instance, if the position of the object is -0.9, and the step_size is 1. This function will return 0. Which is wrong, since the closest node should be -1. If the position is -1.1 however, it will return -1 correctly. Explaining picture (copy&paste the url, external linking disabled by host): http://hem.passagen.se/storage/1d-grid.gif Thanks in advance if anyone can crack this nut.

##### Share on other sites
float get_closest_snap_pos(float pos, float step_size){	return round(pos/step_size)*step_size;}

Should work

round can be implemented as
inline double round(const double num){       return std::floor(num+0.5);}

[/edit]

[Edited by - Cocalus on April 19, 2006 7:04:19 AM]

##### Share on other sites
thank you so much! works wonderful, this saved my day =)