[英]Line Intersection - getting incorrect result
我正在嘗試編寫一個函數,通過獲取方程的標准形式並求解x和y來計算線相交。
我按照有關編碼數學的視頻(第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;
}
}
試試看
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.