Skip to main content
gamedev.net
🔒 Locked

Approximating numbers.

Started by Calin Dec 9, 2005 at 5:12 PM 2 replies 650+ views
Original Post
Calin
Calin
I am making a SimCity type of game. I am trying to make a 'snap to grid' function in the game. I have the mouse screen position and I would like to aproximate it to the nearest grid line position. I have a grid line every five pixels so for instance if the mouse position will be 432 the position has to be approximated to 430, for 548 the approximated position should be 550.
My project`s facebook page is “DreamLand Page”
owl
owl
if the grid were parallel to the screen borders you could do something like:

cel_pos: Round((mouse_pos/total_grid_size)*cell_size)

Total grid width: 100
Cell width: 10
Cells in a row: 10
Mouse X: 56

Selected cell column: Round((56/100)*10) = 5.6 ~= 5

It would be the cell at column 5.
[size="2"]I like the Walrus best.
Calin
Calin
Thanks owl!
My project`s facebook page is “DreamLand Page”
illiyada
illiyada
Something like this:
  int snap_to_grid( const int position, const int grid_size )  {    return ((position+grid_size/2)/grid_size)*grid_size;      }


Please note that it will not work correctly with irregular or non-axis-aligned grids. Nor with negative positions.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.