public static bool LineLineIntersection(out Vector3 intersection, Vector3 linePoint1, Vector3 lineVec1, Vector3 linePoint2, Vector3 lineVec2)
{
intersection = Vector3.zero;
Vector3 lineVec3 = linePoint2 - linePoint1;
Vector3 crossVec1and2 = Vector3.Cross(lineVec1, lineVec2);
Vector3 crossVec3and2 = Vector3.Cross(lineVec3, lineVec2);
float planarFactor = Vector3.Dot(lineVec3, crossVec1and2);
//Lines are not coplanar. Take into account rounding errors.
if((planarFactor >= 0.00001f) || (planarFactor <= -0.00001f)){
return false;
}
//Note: sqrMagnitude does x*x+y*y+z*z on the input vector.
float s = Vector3.Dot(crossVec3and2, crossVec1and2) / crossVec1and2.sqrMagnitude;
if((s >= 0.0f) && (s <= 1.0f)){
intersection = linePoint1 + (lineVec1 * s);
return true;
}
else{
return false;
}
}