DSGM_Intersection

This commit is contained in:
CTurt 2015-02-01 18:03:27 +00:00
parent 8e58beac54
commit fcd4a27f47
2 changed files with 44 additions and 0 deletions

View File

@ -18,3 +18,5 @@ inline int DSGM_Random(int min, int max);
void DSGM_Delay(unsigned int time);
size_t DSGM_GetWordLength(char *text);
bool DSGM_Intersection(int Ax, int Ay, int Bx, int By, int Cx, int Cy, int Dx, int Dy);

View File

@ -124,3 +124,45 @@ unsigned int DSGM_GetWordLength(char *text) {
return i;
}
// Taken from: http://alienryderflex.com/intersect/
bool DSGM_Intersection(int Ax, int Ay, int Bx, int By, int Cx, int Cy, int Dx, int Dy) {
int distAB, theCos, theSin, newX, ABpos;
// Fail if either line segment is zero-length
if((Ax == Bx && Ay == By) || (Cx == Dx && Cy == Dy)) return false;
// Fail if the segments share an end-point
if((Ax == Cx && Ay == Cy) || (Bx == Cx && By == Cy) || (Ax == Dx && Ay == Dy) || (Bx == Dx && By == Dy)) return false;
// Translate the system so that point A is on the origin
Bx -= Ax; By -= Ay;
Cx -= Ax; Cy -= Ay;
Dx -= Ax; Dy -= Ay;
// Discover the length of segment A-B
distAB = sqrt32(Bx * Bx + By * By);
// Rotate the system so that point B is on the positive X axis
theCos = Bx / distAB;
theSin = By / distAB;
newX = Cx * theCos + Cy * theSin;
Cy = Cy * theCos - Cx * theSin; Cx = newX;
newX = Dx * theCos + Dy * theSin;
Dy = Dy * theCos - Dx * theSin; Dx = newX;
// Fail if segment C-D doesn't cross line A-B
if((Cy < 0 && Dy < 0) || (Cy >= 0 && Dy >= 0)) return false;
// Discover the position of the intersection point along line A-B
ABpos = Dx + (Cx - Dx) * Dy / (Dy - Cy);
// Fail if segment C-D crosses line A-B outside of segment A-B
if(ABpos < 0 || ABpos > distAB) return false;
// Apply the discovered position to line A-B in the original coordinate system
// *X = Ax + ABpos * theCos;
// *Y = Ay + ABpos * theSin;
return true;
}