简体   繁体   中英

Line Intersection - getting incorrect result

I am trying to write a function to calculate the line intersection by getting the standard form of the equations and solving for x and y.

I followed the videos on Coding Math, episodes 32 and 33 , and looked at the javascript version in his repo , but my version doesn't get the right answer.

#include <iostream>
#include <optional>

struct Point { float x, y; };

std::ostream& operator<<( std::ostream& out, Point point ) {
    return out << '(' << point.x << ',' << point.y << ')';
}

struct LineSegment { Point a, b; };

std::ostream& operator<<( std::ostream& out, const LineSegment& lineSegment ) {
    return out << '(' << lineSegment.a << ',' << lineSegment.b << ')';
}

/**
 * Takes two line segments and returns the intersection of the lines they lie on
 * If the lines are parallel or collinear returns an empty optional
 * @param p
 * @param q
 * @return
 */
std::optional<Point> lineIntersect( const LineSegment& p, const LineSegment& q ) {
    // variables are named for normal form of line Ax + By = C
    float pa = p.b.y - p.a.y;
    float pb = p.a.x - p.b.y;
    float pc = pa * p.a.x + pb * p.a.y;
    float qa = q.b.y - q.a.y;
    float qb = q.a.x - q.b.y;
    float qc = qa * q.a.x - qb * q.a.y;

    float denominator = pa * qb - qa * pb;

    if ( denominator == 0 ) return std::nullopt;

    return Point{
            ( qb * pc - pb * qc ) / denominator,
            ( pa * qc - qa * pc ) / denominator
    };
}

int main() {
    LineSegment p{{ 0, 0 },
                  { 2, 2 }};
    LineSegment q{{ 0, 2 },
                  { 2, 0 }};

    auto intersection = lineIntersect( p, q );

    std::cout << "Lines " << p << " and " << q << ' ';

    if ( intersection ) {
        std::cout << "intersect at " << *intersection << std::endl;
    }
    else {
        std::cout << "do not intersect" << std::endl;
    }
}

Try with

float pa = p.b.y - p.a.y;
float pb = p.a.x - p.b.x;                 <- p.b.x & not p.b.y
float pc = pa * p.a.x + pb * p.a.y;
float qa = q.b.y - q.a.y;
float qb = q.a.x - q.b.y;
float qc = qa * q.a.x - qb * q.a.y;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM