This should be fairly simple since you only need to check if it crosses the x-axis or the y-axis. You can just check if any one of your x
s or y
s shifts from positive to negative or negative to positive.
def intersects_axis(v1, v2):
return (v1 <= 0 <= v2 or v2 <= 0 <= v1)
def determine_intersections(x1, y1, x2, y2):
print("Checking if {}, {} and {}, {} any axes".format(x1, y1, x2, y2))
intersects_y = intersects_axis(y1, y2)
intersects_x = intersects_axis(x1, x2)
if intersects_y and intersects_x:
print("Line crosses both x and y axes")
elif intersects_y:
print("Line crosses y axis only")
elif intersects_x:
print("Line crosses x axis only")
else:
print("Line does not cross both x and y axes")
if __name__ == "__main__":
x1, y1 = 1, 1
x2, y2 = 2, 2
determine_intersections(x1, y1, x2, y2)
x2, y2 = 1, -1
determine_intersections(x1, y1, x2, y2)
x2, y2 = -1, -1
determine_intersections(x1, y1, x2, y2)
x2, y2 = -1, 1
determine_intersections(x1, y1, x2, y2)
Which will give you:
Checking if 1, 1 and 2, 2 any axes
Line does not cross both x and y axes
Checking if 1, 1 and 1, -1 any axes
Line crosses y axis only
Checking if 1, 1 and -1, -1 any axes
Line crosses both x and y axes
Checking if 1, 1 and -1, 1 any axes
Line crosses x axis only