Last active
October 14, 2017 05:15
-
-
Save kndt84/efc217b1a57ca4bba036aa0c05682ad6 to your computer and use it in GitHub Desktop.
C++ function which tests whether two lines are intersected
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int intersection(Point2i p1, Point2i p2, Point2i p3, Point2i p4) { | |
// Store the values for fast access and easy | |
// equations-to-code conversion | |
int x1 = p1.x, x2 = p2.x, x3 = p3.x, x4 = p4.x; | |
int y1 = p1.y, y2 = p2.y, y3 = p3.y, y4 = p4.y; | |
int d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); | |
// If d is zero, there is no intersection | |
if (d == 0) return 0; | |
// Get the x and y | |
int pre = (x1*y2 - y1*x2); | |
int post = (x3*y4 - y3*x4); | |
float x = ( pre * (x3 - x4) - (x1 - x2) * post ) / d; | |
float y = ( pre * (y3 - y4) - (y1 - y2) * post ) / d; | |
// Check if the x and y coordinates are within both lines | |
if ( x < min(x1, x2) || x > max(x1, x2) || x < min(x3, x4) || x > max(x3, x4) ) return 0; | |
if ( y < min(y1, y2) || y > max(y1, y2) || y < min(y3, y4) || y > max(y3, y4) ) return 0; | |
int td = (x1 - x2) * (y4 - y1) + (y1 - y2) * (x1 - x4); | |
if ( td > 0 ) return 1; | |
if ( td < 0 ) return -1; | |
// Return the point of intersection | |
// Point2f* ret = new Point2f(); | |
// ret.x=x; | |
// ret.y=y; | |
// return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment