c++ - Evaluating the intersection point with a vertical line involved -
here function returning intersection point between 2 lines defined points p0, p1
, p2, p3
:
#include "std_lib_facilities.h" #include <iostream> struct point{ point(int xx, int yy): x(xx), y(yy) { } int x; int y; }; // find intersection of 2 lines point intersectpoint(point& p0, point& p1, point& p2, point& p3){ // line formed p0p1 double dx1 = p1.x - p0.x; double dy1 = p1.y - p0.y; double m1 = dy1 / dx1; double c1 = p1.y - m1 * p1.x; cout <<"m1: "<< m1 <<'\n'; // line formed p2p3 double dx2 = p3.x - p2.x; double dy2 = p3.y - p2.y; double m2 = dy2 / dx2; double c2 = p3.y - m1 * p3.x; cout <<"m2: "<< m2 <<'\n'; // find intersection point double epsilon = 1e-6; // (-1,-1) represents no intersection if (abs(m1 - m2) < epsilon) return point(-1,-1); else{ double interx = (c2 - c1) / (m1 - m2); double intery = m1 * interx + c1; cout <<"(interx, intery): "<< interx <<", "<< intery <<'\n'; return point(interx, intery); } } //------------------------------------------------------------------------------------------------ int main(){ point verticalstart(100, 100); point verticalend(100,300); point horizontalstart(50,200); point horizontalend(150,200); point intersection = intersectpoint(horizontalstart ,horizontalend, verticalstart, verticalend); cout <<"returned value: \n"; cout << "( "<< intersection.x <<", "<< intersection.y <<" )\n"; getchar(); return 0; }
in case of intersection between vertical , horizontal output:
m1: 0 m2: 1.#inf (interx, intery): -0, 200 returned value: ( 0, 200 )
question:
how handle case, function returns valid points of intersection?
note: code compiled on mvs2010.
i suggest not use slope-intercept representation, i.e.: y = a*x + b
vector-parametric representation:
pa = (p1-p0)*t + p0 pb = (p3-p2)*u + p2
in way lines x = k
have representation.
solve system variables t
, u
(2 variables, 2 equations, 2 coordinates x
, y
) pa = pb
(the intersection point) , back-substitute in 1 of these equations intersection point.
Comments
Post a Comment