Home > Blockchain >  How do I calculate if a point falls on a line within a grid?
How do I calculate if a point falls on a line within a grid?

Time:09-21

I have a grid where each box is NxN. I can rotate that grid by A degrees. (So if A is 45, then each line in the grid is 45 degrees or 135 degrees).

Given a grid box size, an angle, and a set of coordinates.. how can I determine if the coordinate [x,y] lies on the grid?

I tried the following, which works for 45 degrees, but no other angles

BOX_SIZE = 2

def on_grid(x: float, y: float) -> bool:
    return x % BOX_SIZE == y % BOX_SIZE

What would a function look like that works regardless of angle, and also takes into account the perpendicular lines?

CodePudding user response:

you could do the following :

from math import tan
def on_grid(a,b,x,y,angle,N):
     n = (1/N)*(y-tan(angle)*(x-a)-b)
     if n<int(n)-10**(-10):
           return True
     else :
           return False

Note::

  • (a,b) is the coordinate of the origin of your grid
  • angle should be different than 90° it define the rotation of the y_axis (x_axis should be horizontal )
  • (x,y) the coordinates of your point
  • N the size of the box
  • I choose n<int(n)-10**(-10) because n define which line is possible the point could be on (it is an integer ) and due to incertitude of the calculation
  • Related