我正在尝试编写一个函数,通过获取方程的标准形式并求解x和y来计算线相交。
我关注了有关编码数学的视频,分别是第32和33集,并查看了his 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;
}
}
答案 0 :(得分:0)
尝试
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;