2013-03-26 108 views
4

所以我一直在用这个相对简单的算法来敲打我的头。我不知道我的代码有什么问题,但我没有得到它们实际相交的交点。找到一条线的交点

我正在使用Unity3D,我试图找到两条线在x,z平面相交的点,但不在x,y平面。我假设适用于x,y的算法应该适用于x,z;

我的代码:

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.forwardthreateningCar.forward通常是要么[0,0,1], [0,0,-1][1,0,0], [-1,0,0]

+0

你是否检查行是否平行,即det == 0?根据您提交的矢量,两辆车都沿着x或z轴移动。而且由于你使用的是浮动,你可以除以0. – 2013-03-26 23:33:51

+0

我不是,但在大多数情况下,他们是垂直的,如果不是完全90度的地方,那么绝对不会平行但 – Jonny 2013-03-26 23:38:06

+0

但在这种情况下,不应该向量的组合是[0,0,1],[-1,0,0]或[1,0,0],[0,0,-1]还是类似的? – 2013-03-26 23:40:21

回答

0

找到了!!!

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;

很多的浪费时间没有:/。

反正这将帮助任何想要做线路交叉口的人。

0

你可以母公司的空游戏物体的车稍微放置在它的(无论是在IDE或启动)前面。这样你就可以安全地得到绘制线条所需的两点。

+0

是的,我会尝试,虽然技术上我不明白为什么我的工作不正常。我有一种感觉,你的解决方案应该这样做。稍后将在家中尝试。谢谢 – Jonny 2013-03-27 13:34:30