Jump to content
  • Advertisement
Sign in to follow this  
peter_b

Finding the closest point in a 1d grid.

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement

float get_closest_snap_pos(float pos, float step_size)
{
return round(pos/step_size)*step_size;
}

Should work

[edit]
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!