C# 求两条直线的交点
所以我一直在研究这个相对简单的算法。我不确定我的代码出了什么问题,但我没有得到它们实际相交的交点 我使用的是Unity3D,我试图找到两条线相交的点,在x,z平面上,虽然不是在x,y平面上。我假设适用于x,y的算法适用于x,z 我的代码:C# 求两条直线的交点,c#,math,geometry,unity3d,C#,Math,Geometry,Unity3d,所以我一直在研究这个相对简单的算法。我不确定我的代码出了什么问题,但我没有得到它们实际相交的交点 我使用的是Unity3D,我试图找到两条线相交的点,在x,z平面上,虽然不是在x,y平面上。我假设适用于x,y的算法适用于x,z 我的代码: Vector3 thisPoint1 = thisCar.position + (2 * thisCar.forward); Vector3 thisPoint2 = thisCar.position + (20 * thisCar.forward); De
Vector3 thisPoint1 = thisCar.position + (2 * thisCar.forward);
Vector3 thisPoint2 = thisCar.position + (20 * thisCar.forward);
Debug.DrawLine(thisPoint1, thisPoint2, Color.white, 2);
Vector3 otherPoint1 = threateningCar.position + (2 * threateningCar.forward);
Vector3 otherPoint2 = threateningCar.position + (20 * threateningCar.forward);
Debug.DrawLine(otherPoint1, otherPoint2, Color.white, 2);
float A1 = thisPoint2.z - thisPoint1.z;
float B1 = thisPoint1.x - thisPoint2.x;
float C1 = A1 * thisPoint1.x + B1 * thisPoint1.z;
float A2 = otherPoint2.z - otherPoint1.z;
float B2 = otherPoint1.x - otherPoint2.x;
float C2 = A2 * otherPoint1.z + B2 * otherPoint1.z;
float det = A1 * B2 - A2 * B1;
float x = (B2 * C1 - B1 * C2) / det;
float z = (A1 * C2 - A2 * C1) / det;
return new Vector3(x, this.transform.position.y, z);
谁能帮我指出我做错了什么
thisCar.forward
和threatingcar.forward
通常是[0,0,1],[0,0,-1]
或[1,0,0],-1,0,0]
您可以将一个空的游戏对象设置为该车的父对象,并将其稍微放在其前面(在IDE中或启动时)。这样你就可以安全地得到画一条线所需的两点。找到了
float A2 = otherPoint2.z - otherPoint1.z;
float B2 = otherPoint1.x - otherPoint2.x;
float C2 = A2 * otherPoint1.z + B2 * otherPoint1.z;
应该是:
float A2 = otherPoint2.z - otherPoint1.z;
float B2 = otherPoint1.x - otherPoint2.x;
float C2=A2*otherPoint1.x
+B2*otherPoint1.z
很多时间白白浪费了:/
无论如何,这将有助于任何想要进行线路交叉的人。如果你知道这辆车需要行驶的距离
t
和另一辆车需要行驶的距离u
,那么交叉点是微不足道的
Vector3 intersection = thisCar.position + (t * thisCar.forward);
Vector3 intersection = threateningCar.position + (u * threateningCar.forward);
但是你可以用一些代数来求解t
和u
,二维向量叉积,[x_1,z_1]×[x_2,z_1]=(x_2 z_1-z_2 x_1)
这是y
三维叉积的标量值
t = Vector3.Cross(threateningCar.forward, thisCar.position - threateningCar.position).y
/ Vector3.Cross(thisCar.forward, threateningCar.forward).y;
u = Vector3.Cross(thisCar.forward, thisCar.position - threateningCar.position).y
/ Vector3.Cross(thisCar.forward, threateningCar.forward).y;
您是否检查这些线是否平行,即det==0?根据您提交的矢量,两辆车都沿x或z轴移动。因为你使用的是float,所以你可以除以0。我不是否定的,但是在大多数情况下,它们是垂直的,如果不是90度的话,那么一定不是平行的。但是在这种情况下,向量的组合不是应该是[0,0,1],-1,0,0]或者[1,0,0],[0,0,-1]或者类似的吗?啊,是的,我想我在这个问题上被误解了。这些都是.forward向量的可能值(在我的模拟中)。我只在车辆处于交叉路口时执行此检查,因此它们很可能彼此成90度角。这就是为什么我不应该使用并行linesWell,代码看起来很好,看不到任何可能的错误。是的,我会试试看,虽然从技术上我看不出为什么我的代码不工作。我觉得你的解决方案应该能做到。稍后我们会在家里试用。谢谢