Cross point of 2 segments
Table of contents
# Explanation
Let 2 segments $S1(p_0, p_1), and their cross point .
S1 can be seen as base of 2 triangles.
2 triangles with vertices and and the common base S1.
Let the heights and .
A height of a triangle can be calculated with its area and length of its base.
Length of base is .
The area can be calculated by using cross product .
2 heights satisfies the proportion below.
Transform it from the point of view of length.
Don't forget that the resultign coordinates can include errors.
# Code
Vector2 crossPoint(Vector2 &p0, Vector2 &p1, Vector2 &p2, Vector2 &p3) {
Vector2 baseSeg = p1 - p0;
Vector2 crossSeg = p3 - p2;
double h1 = fabs(baseSeg.cross(p2 - p0)) / (baseSeg.length() * 2);
double h2 = fabs(baseSeg.cross(p3 - p0)) / (baseSeg.length() * 2);
Vector2 p = p2 + crossSeg * h1 / (h1 + h2);
if (fabs(p.x) < EPS) p.x = 0.0;
if (fabs(p.y) < EPS) p.y = 0.0;
return p;
}
Shun
Remote freelancer. A web and mobile application enginner.
Traveling around the world based on East Asia.
I'm looking forward to your job offers from all over the world!