Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the intersection between two lines

So I've been banging my head over this relatively simple algorithm. I'm not sure what's wrong in my code yet I'm not getting the intersection point where they are actually intersecting.

I'm using Unity3D and I'm trying to find the point where two lines intersect, in the x,z plane though not in the x, y plane. I am assuming that the algorithm which works for x,y should work for x,z;

My code:

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);

Can anyone help into pointing out what I'm doing wrong?

thisCar.forward and threateningCar.forward are usually either [0,0,1], [0,0,-1] or [1,0,0], [-1,0,0]

like image 522
Jonny Avatar asked Oct 22 '22 13:10

Jonny


1 Answers

Found it!!!

float A2 = otherPoint2.z - otherPoint1.z;
float B2 = otherPoint1.x - otherPoint2.x;
float C2 = A2 * otherPoint1.z + B2 * otherPoint1.z;

Should be:

float A2 = otherPoint2.z - otherPoint1.z;
float B2 = otherPoint1.x - otherPoint2.x; 

float C2 = A2 * otherPoint1.x + B2 * otherPoint1.z;

Lot's of wasted time for nothing :/.

Anyways this will help anyone looking to do line intersection.

like image 133
Jonny Avatar answered Oct 24 '22 04:10

Jonny