Skip to content

Instantly share code, notes, and snippets.

@BrunoVandekerkhove
Created April 28, 2018 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrunoVandekerkhove/46aa7fac3bcc0929b99bc686529afc1e to your computer and use it in GitHub Desktop.
Save BrunoVandekerkhove/46aa7fac3bcc0929b99bc686529afc1e to your computer and use it in GitHub Desktop.
Intersection of circle with line (fixed radius)
#define RHO 400.0 // Circle radius
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_circle_intersection(
segment line, segment circle,
point_2Df *firstIntersection, point_2Df *secondIntersection /* Cannot be NULL */) {
float dx = line.x2-line.x1, dy = line.y2-line.y1;
float l = sqrtf(dx*dx+dy*dy); // Length of line
float dxl = dx/l, dyl = dy/l;
float t = dxl*(circle.x1-line.x1) + dyl*(circle.y1-line.y1); // Projection of circle center on line
float ex = t*dxl + line.x1, ey = t*dyl + line.y1; // Coordinates of e on line and closest to circle center
float lec = sqrtf((ex-circle.x1)*(ex-circle.x1) + (ey-circle.y1)*(ey-circle.y1)); // Distance e to circle center
if (lec < RHO) { // Intersection
float dt = sqrtf(RHO*RHO - lec*lec); // Distance to to circle intersection point
int nbi = 0;
if (t-dt >=0 && t-dt <= l) {
firstIntersection->x = (t-dt) * dxl + line.x1;
firstIntersection->y = (t-dt) * dyl + line.y1;
nbi = 1;
}
if (t+dt >=0 && t+dt <= l) {
if (nbi == 0) {
firstIntersection->x = (t+dt) * dxl + line.x1;
firstIntersection->y = (t+dt) * dyl + line.y1;
nbi = 1;
}
else {
secondIntersection->x = (t+dt) * dxl + line.x1;
secondIntersection->y = (t+dt) * dyl + line.y1;
nbi = 2;
}
}
return nbi;
}
else if (lec == RHO && t >=0 && t <= l) { // Tangent
firstIntersection->x = ex;
firstIntersection->y = ex;
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment