// 2D yes-or-no intersection test for a pair of line segments public static bool LineSegmentIntersection2D(Vec2 a_begin, Vec2 a_end, Vec2 b_begin, Vec2 b_end) { Vec2 a_dir = a_end - a_begin; Vec2 b_dir = b_end - b_begin; Vec2 a_normal = new Vec2 { x = a_dir.y, y = -a_dir.x }; a_normal /= a_normal.ComputeMagnitude(); Vec2 b_normal = new Vec2 { x = b_dir.y, y = -b_dir.x }; b_normal /= b_normal.ComputeMagnitude(); double a_offset = Vec2.Dot(a_normal, a_begin); double b_offset = Vec2.Dot(b_normal, b_begin); double a_dir_dot = Vec2.Dot(a_dir, b_normal); double a_origin_dot = Vec2.Dot(a_begin, b_normal); double a_hit = (b_offset - a_origin_dot) / a_dir_dot; double b_dir_dot = Vec2.Dot(b_dir, a_normal); double b_origin_dot = Vec2.Dot(b_begin, a_normal); double b_hit = (a_offset - b_origin_dot) / b_dir_dot; Vec2 a_intersect = a_begin + a_dir * a_hit; Vec2 b_intersect = b_begin + b_dir * b_hit; return(a_hit >= 0 && a_hit <= 1 && b_hit >= 0 && b_hit <= 1); }