Created
April 28, 2018 08:48
-
-
Save BrunoVandekerkhove/14e7ef1c63b7c31b9b49a082b3817317 to your computer and use it in GitHub Desktop.
Intersection of 2 line segments
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
typedef struct point2df_struct { | |
float x; | |
float y; | |
} point_2Df; | |
typedef struct segment_struct { | |
float x1; | |
float y1; | |
float x2; | |
float y2; | |
} segment; | |
short get_line_line_intersection(segment s1, segment s2, | |
point_2Df *intersection /* Cannot be NULL */) { | |
float s1_x = s1.x2 - s1.x1, s1_y = s1.y2 - s1.y1; | |
float s2_x = s2.x2 - s2.x1, s2_y = s2.y2 - s2.y1; | |
float s = (-s1_y * (s1.x1 - s2.x1) + s1_x * (s1.y1 - s2.y1)) / (-s2_x * s1_y + s1_x * s2_y); | |
float t = ( s2_x * (s1.y1 - s2.y1) - s2_y * (s1.x1 - s2.x1)) / (-s2_x * s1_y + s1_x * s2_y); | |
if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { | |
intersection->x = s1.x1 + (t * s1_x); | |
intersection->y = s1.y1 + (t * s1_y); | |
return 1; | |
} | |
return 0; // No collision | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment