[英]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. 我正在尝试编写一个函数,通过获取方程的标准形式并求解x和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. 我按照有关编码数学的视频(第32和33集)进行了观看,并查看了他的repo中的javascript版本,但是我的版本没有得到正确的答案。
#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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.