Skip to content

Instantly share code, notes, and snippets.

@FloooD
Created March 18, 2011 18:22
Show Gist options
  • Select an option

  • Save FloooD/876568 to your computer and use it in GitHub Desktop.

Select an option

Save FloooD/876568 to your computer and use it in GitHub Desktop.
gets first collision between line segment and square
inline int line_square_collision(float ex, float ey, float sqx, float sqy, float sqhlen, float *ox, float *oy)
{
if (!ox) {float x; ox = &x;}
if (!oy) {float y; oy = &y;}
int cx = (fabsf(sqx) <= sqhlen);
int cy = (fabsf(sqy) <= sqhlen);
if (cx && cy) {
if (fabsf(ex - sqx) <= sqhlen && fabsf(ey - sqy) <= sqhlen) {
*ox = ex; *oy = ey;
return 1;
}
sqhlen *= -1;
}
*ox = (ex >= 0) ? sqx - sqhlen : sqx + sqhlen;
*oy = (ey >= 0) ? sqy - sqhlen : sqy + sqhlen;
if ((ex != 0) && ((!(cx ^ cy) && ((fabsf(ey * *ox) >= fabsf(ex * *oy)) ^ (sqhlen < 0))) || (cy && !cx)))
goto collision;
if (ey == 0) goto no_collision;
float temp = ex; ex = ey, ey = temp;
temp = sqx; sqx = sqy; sqy = temp;
float *tptr; tptr = ox; ox = oy; oy = tptr;
collision:
if ((*ox * ex >= 0) && (fabsf(*ox) <= fabsf(ex))) {
*oy = (*ox) * ey / ex;
if (fabsf(*oy - sqy) <= fabsf(sqhlen))
return 1;
}
no_collision:
return (*ox = *oy = 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment