S
S
Singerofthefall2013-01-11 11:31:08
Algorithms
Singerofthefall, 2013-01-11 11:31:08

How to determine which of the grid nodes is closer to the point?

There is a coordinate grid with a certain step, say, a (the step is the same both horizontally and vertically). There is also some point P with coordinates (x,y) . What is the best way to determine the coordinates of the grid node that will be closest to this point?
It looks something like this - I get the coordinates of a mouse click (colored dots on a white background in the picture), and I need to find the node closest to them (points of the corresponding color in the nodes in the picture):
4960d762e040457e5ce412f59d2bd4b2.jpg
The only thing that came to my mind was to divide the coordinates of the point by the grid step; this way we get the coordinates of the node to the left (x-axis increases from left to right) and below (y-axis increases from bottom to top) of our point, and then iterate over the 4 nearest nodes and stupidly compare the difference in coordinates. Tell me a better way, please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bay73, 2013-01-11
@Singerofthefall

If mod(x, a) < a/2, then it is closer to the left than to the right.
If mod(y,a) < a/2, then closer to the bottom than to the top

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question