Skip to content

Instantly share code, notes, and snippets.

@Shaptic
Created September 27, 2012 22:54
Show Gist options
  • Save Shaptic/3796950 to your computer and use it in GitHub Desktop.
Save Shaptic/3796950 to your computer and use it in GitHub Desktop.
Checks whether two line-segments interset.
/**
* Checks for intersection with another line segment. Touching at
* endpoints qualifies as intersections.
*
* @param math::CRay2 The other line
*
* @return TRUE if they intersect, FALSE otherwise.
* @see http://gamedev.stackexchange.com/questions/26004/how-to-detect-2d-line-on-line-collision
**/
bool CRay2::CheckCollision(const CRay2& Other, math::CVector2* p_Intersection) const
{
/**
* Solve for the intersection point.
*
* Derivation:
* First line: y - y1 = m1(x - x1)
* Second line: y - y2 = m2(x - x2)
* Equal to each other: m1x - m1x1 + y1 = m2x - m2x2 + y2
* Solve for 'x': m1x - m2x = -m2x2 + y2 + m1x1 + y1
* x(m1 - m2) = -m2x2 + y2 + m1x1 + y1
* x = (-m2x2 + y2 + m1x1 + y1) / (m1 - m2)
* Solve for 'y': y = m1(x) - m1x1 + y1
* Thus (x, y) becomes the intersection point.
*
* Then we must see if (x, y) is in the range of line segments given.
**/
math::CVector2 Intersect;
float m1, m2;
m1 = this->GetSlope();
m2 = Other.GetSlope();
// Test for infinite slopes or parallel lines.
if(this->Start.x == this->End.x)
Intersect.x = this->Start.x;
else if(Other.Start.x == Other.End.x)
Intersect.x = Other.Start.x;
else if(m1 == m2)
return false;
else
Intersect.x = (-m2 * Other.Start.x + Other.Start.y + m1 * this->Start.x - this->Start.y) / (m1 - m2);
Intersect.y = m1 * Intersect.x - m1 * this->Start.x + this->Start.y;
if(this->OnRay(Intersect) && Other.OnRay(Intersect))
{
if(p_Intersection != NULL)
*p_Intersection = Intersect;
return true;
}
else
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment