This code is a function that determines if two lines intersect and returns the intersection point as the coordinates (x,y). The function takes in the starting and ending x and y coordinates for each line as arguments. The function first calculates the slope and length of each line. It then uses these values to determine if the lines intersect and, if they do, calculates the intersection point. The function returns a boolean value indicating whether the lines intersect, as well as the x and y coordinates of the intersection point. The function is called in a loop that clears the screen, draws the two lines with the mouse coordinates as one of the endpoints, and prints the intersection point (if the lines intersect).
PlayBASIC Code:
Do // Clear the screen Cls // Set line1StartX, line1StartY, line1EndX, and line1EndY to variables line1StartX=100 line1StartY=100 line1EndX = mousex() line1EndY = mousey() // Set line2StartX, line2StartY, line2EndX, and line2EndY to variables line2StartX=20 line2StartY=200 line2EndX=1000 line2EndY=700 // Draw line1 in black linec line1StartX, line1StartY, line1EndX, line1EndY,-1 // Draw line2 in green linec line2StartX, line2StartY, line2EndX, line2EndY,$00ff00 // Check if lines intersect State,x#,y#=Lines_Intersect(line1StartX, line1StartY, line1EndX, line1EndY,_ line2StartX, line2StartY, line2EndX, line2EndY) // Print intersect state print State // If lines intersect, draw a red circle at intersect point if State Circlec X#,y#,10,true,$ff0000 endif // Display the screen sync loop spacekey() end Function Lines_Intersect(line1StartX, line1StartY, line1EndX, line1EndY, line2StartX, line2StartY, line2EndX, line2EndY) // Initialize variables intersects = False intersectX = 0 intersectY = 0 s1_x# = line1EndX - line1StartX s1_y# = line1EndY - line1StartY s2_x# = line2EndX - line2StartX s2_y# = line2EndY - line2StartY // Calculate s and t s# = (-s1_y# * (line1StartX - line2StartX) + s1_x# * (line1StartY - line2StartY)) / (-s2_x# * s1_y# + s1_x# * s2_y#) t# = ( s2_x# * (line1StartY - line2StartY) - s2_y# * (line1StartX - line2StartX)) / (-s2_x# * s1_y# + s1_x# * s2_y#) // Check if s and t are within valid range if s# >= 0 and s# <= 1 and t# >= 0 and t# <= 1 // Set intersects to true and calculate intersectX and intersectY intersects = True intersectX# = line1StartX + (t# * s1_x#) intersectY# = line1StartY + (t# * s1_y#) EndIf // Return intersects, intersectX, and intersectY EndFunction intersects, intersectX#, intersectY#