Fast line segment interaction in three-space
I'm pretty proud of this code, seeing that I just learned the basics of linear algebra and vector math yesterday.
/**
* Checks for a collision between two line segments.
* RoyAwesome says rays are line segments.
*
* Perhaps Roy needs to brush up on geometry then
*
* Code based on http://www.bryceboe.com/2006/10/23/line-segment-intersection-algorithm/
*
* @param a
* @param b
* @return
*/
public static boolean checkCollision(Segment a, Segment b) {
return (ccw(a.origin, b.origin, b.endpoint) != ccw(a.endpoint, b.origin, b.endpoint))
&& (ccw(b.origin, a.origin, a.endpoint) != ccw(b.endpoint, a.origin, a.endpoint));
}
/**
* Checks if 3 points are counterclockwise.
* (A helper for a helper method)
* @param a
* @param b
* @param c
* @return
*/
private static boolean ccw(Vector3 a, Vector3 b, Vector3 c) {
//This is Java lisp
return (c.getY() - a.getY()) * (b.getX() - a.getX())
< (b.getY() - a.getY()) * (c.getX() - a.getX())
|| (c.getY() - a.getY()) * (b.getZ() - a.getZ())
< ((b.getY() - a.getY()) * (c.getZ() - a.getZ()));
}
As it says in the comments, I borrowed the original idea from this guy.
Thanks for reading my post! If you enjoyed it or it helped you, please consider liking/tweeting this page, commenting, or following me on GitHub or Twitter!