Algorithm to Detect a Click Within Square Range

algorithmsmath

It might be a simple question but I am looking for optimal solution. I will have numbers printed on a screen and I will be aware of coordinates. Numbers/Symbols will have 4 points(Square) to define their boundaries. Coordinates of that particular symbol will be stored in a file. Lets' say there is a number 5 and it's 4 coordinates on screens are:(2,20,20,20,2,40,20,40)

Now lets assume that a string 555 represent a value in a file, say the value is Car1

When the user press num pad of 5 thrice then it should detect that he needs Car1.

I am interested to know whether there's some standard formula/Algo to find the range between these 4 coordinates or I have to work on my own. The Formula that was coming in my mind is:

Symbol = (X1+X2+X3+X4)(Y1+Y2+Y3+Y4) = (62)(120) = 182(Representing 5)

But I am skeptical whether it's right and whether the formula will always be given a unique value per symbol/character based on given coordinates?

Best Answer

A common way to do this is just to compare the coordinates of the mouse click with the coordinates of the square.

Suppose the square has top-left coordinate of x1, y1 and bottom-right is x2,y2.

A mouse click at mx, my is in the square if (mx>x1 and mx<x2 and my>y1 and my<y2).


If all the square are the same size and in a grid, you can give each square a number:

n = y * number of squares in a row + x.

Then to get n from a mouse click:

n = (width of grid in pixels / square width in pixels * number of squares in a row) + (height of grid in pixels / square height in pixels)