Created
July 19, 2012 19:28
-
-
Save Shaptic/3146193 to your computer and use it in GitHub Desktop.
Line and line collision detection
This file contains hidden or 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
/** | |
* Checks for intersection with another line segment. Touching at | |
* endpoints qualifies as intersections. | |
* | |
* @param math::Ray2 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 Ray2::CheckCollision(const Ray2& Other) 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::Vector2 Intersect; | |
float m1, m2; | |
m1 = this->GetSlope(); | |
m2 = Other.GetSlope(); | |
// Test for infinite slopes or parallel lines. | |
if(this->Start.GetX() == this->End.GetX()) | |
Intersect.SetX(this->Start.GetX()); | |
else if(Other.Start.GetX() == Other.End.GetX()) | |
Intersect.SetX(Other.Start.GetX()); | |
else if(m1 == m2) | |
return false; | |
else | |
Intersect.SetX((-m2 * Other.Start.GetX() + Other.Start.GetY() + m1 * this->Start.GetX() - this->Start.GetY()) / (m1 - m2)); | |
Intersect.SetY(m1 * Intersect.GetX() - m1 * this->Start.GetX() + this->Start.GetY()); | |
return this->OnRay(Intersect) && Other.OnRay(Intersect); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment