两条线相交的算法?
我有2行。两条线都包含 X 和 Y 两个点。这意味着它们都有长度。
我看到两个公式,一个使用行列式,一个使用普通代数。哪个计算效率最高?公式是什么样的?
我很难在代码中使用矩阵。
这就是我目前所拥有的,它可以更有效吗?
public static Vector3 Intersect(Vector3 line1V1, Vector3 line1V2, Vector3 line2V1, Vector3 line2V2)
{
//Line1
float A1 = line1V2.Y - line1V1.Y;
float B1 = line1V1.X - line1V2.X;
float C1 = A1*line1V1.X + B1*line1V1.Y;
//Line2
float A2 = line2V2.Y - line2V1.Y;
float B2 = line2V1.X - line2V2.X;
float C2 = A2 * line2V1.X + B2 * line2V1.Y;
float det = A1*B2 - A2*B1;
if (det == 0)
{
return null;//parallel lines
}
else
{
float x = (B2*C1 - B1*C2)/det;
float y = (A1 * C2 - A2 * C1) / det;
return new Vector3(x,y,0);
}
}
I have 2 lines. Both lines containing their 2 points of X and Y. This means they both have length.
I see 2 formulas, one using determinants and one using normal algebra. Which would be the most efficient to calculate and what does the formula looks like?
I'm having a hard time using matrices in code.
This is what I have so far, can it be more efficient?
public static Vector3 Intersect(Vector3 line1V1, Vector3 line1V2, Vector3 line2V1, Vector3 line2V2)
{
//Line1
float A1 = line1V2.Y - line1V1.Y;
float B1 = line1V1.X - line1V2.X;
float C1 = A1*line1V1.X + B1*line1V1.Y;
//Line2
float A2 = line2V2.Y - line2V1.Y;
float B2 = line2V1.X - line2V2.X;
float C2 = A2 * line2V1.X + B2 * line2V1.Y;
float det = A1*B2 - A2*B1;
if (det == 0)
{
return null;//parallel lines
}
else
{
float x = (B2*C1 - B1*C2)/det;
float y = (A1 * C2 - A2 * C1) / det;
return new Vector3(x,y,0);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设您有两行
Ax + By = C
形式的行,您可以很容易地找到它:从 此处
Assuming you have two lines of the form
Ax + By = C
, you can find it pretty easily:Pulled from here
我最近重新回到纸上,用基本代数找到了这个问题的解决方案。我们只需要求解两条直线形成的方程,如果存在有效解,则存在交点。
您可以检查我的 Github 存储库以获取扩展的实现处理 double 和 测试。
I recently went back on paper to find a solution to this problem using basic algebra. We just need to solve the equations formed by the two lines and if a valid solution exist then there is an intersection.
You can check my Github repository for extended implementation handling potential precision issue with double and tests.
如何找到两条线/线段/射线与矩形完整样本的交点
[此处][1]描述了
How to find intersection of two lines/segments/ray with rectangle
full sample is described [here][1]
我在其他地方找到了解决方案并将其简化到我不知道它是如何工作的但它通过了我的所有测试
I found solution somwhere else and simplified it to the point that i don't know how it works but it passes all my tests