/// <summary> /// Computes an intersection of the line and the sphere /// </summary> public static bool LineSphere(Vector3 lineOrigin, Vector3 lineDirection, Vector3 sphereCenter, float sphereRadius, out IntersectionLineSphere intersection) { Vector3 originToCenter = sphereCenter - lineOrigin; float centerProjection = Vector3.Dot(lineDirection, originToCenter); float sqrDistanceToLine = originToCenter.sqrMagnitude - centerProjection * centerProjection; float sqrDistanceToIntersection = sphereRadius * sphereRadius - sqrDistanceToLine; if (sqrDistanceToIntersection < -Geometry.Epsilon) { intersection = IntersectionLineSphere.None(); return(false); } if (sqrDistanceToIntersection < Geometry.Epsilon) { intersection = IntersectionLineSphere.Point(lineOrigin + lineDirection * centerProjection); return(true); } float distanceToIntersection = Mathf.Sqrt(sqrDistanceToIntersection); float distanceA = centerProjection - distanceToIntersection; float distanceB = centerProjection + distanceToIntersection; Vector3 pointA = lineOrigin + lineDirection * distanceA; Vector3 pointB = lineOrigin + lineDirection * distanceB; intersection = IntersectionLineSphere.TwoPoints(pointA, pointB); return(true); }
/// <summary> /// Computes an intersection of the line and the sphere /// </summary> public static bool LineSphere(Line3 line, Sphere sphere, out IntersectionLineSphere intersection) { return(LineSphere(line.origin, line.direction, sphere.center, sphere.radius, out intersection)); }