0

I'm trying to create code that does calculation to know if the line is passing through the rectangle (obstacle), since I only know the position of sta1 and sta2 and I also know the x_min, x_max and y_min, y_max of the rectangle.

enter image description here

sta1 position(x,y) = (1,5) sta2 position(x,y) = (5,1)

retangle x_min = 3 retangle x_max = 4

retangle y_min = 2 retangle y_max = 3

I already have the function that returns the position of the stations:

sta1.position
(1,5)

I also already have the code to get the Euclidean distance between the points:

distance sta1 sta2
example: 20

That is, I need a code where given two points (x, y), and an obstacle that is a rectangle (x,_min, x_max, y_min, y_max), the output of the code informs if there is a line of sight or if the obstacle is in the middle of the way.

Some help in python doing this calculation would help.

searcher__dm01
  • 109
  • 1
  • 8
  • 2
    Does this answer your question? [How to check if line segment intersects a rectangle?](https://stackoverflow.com/questions/16203760/how-to-check-if-line-segment-intersects-a-rectangle) – Dash Nov 26 '22 at 01:39
  • 1
    From the two endpoints, you can make the formula for a line (mx+b). Given that, you can check the four points of the rectangle and see if they are all on the same side of the line. – Tim Roberts Nov 26 '22 at 01:53

1 Answers1

0

I solved using the equation of the line:

# line/rectangle intersection (obstacle)

# node coordinates
source_x = 1
source_y = 5

destination_x = 5
destination_y = 1

# rectangle vertices

vertices_x = [3, 3, 4, 4]
vertices_y = [3, 2, 3, 2]

# Reduced equation of the line
# y = ax + b

# 1 - find the slope
# a = y2 - y1/x2 - x1

a = (destination_y - source_y) / (destination_x - source_x)

# 2 - find the linear coefficient

b = source_y - (a * source_x)

# f(x) = -(a*x) + y-(b)

signal_first = ''
result = ''
signal = ''
for i in range(0, 4):
    fx = -(a * vertices_x[i]) + vertices_y[i] - (b)
    if i == 0:
        value = fx
        if value > 0:
            signal_first = 'positive'
        elif value < 0:
            signal_first = 'negative'
    if fx > 0:
        signal = 'positive'
    elif fx < 0:
        signal = 'negative'

    if signal != signal_first:
        result = 'stations have no line of sight'

print(result)
searcher__dm01
  • 109
  • 1
  • 8