ray sphere intersection equation
Certainly, here is the equation for checking the intersection between a ray and a sphere in C++:
bool raySphereIntersect(Vector3 rayOrigin, Vector3 rayDirection, Vector3 sphereCenter, float sphereRadius) {
Vector3 oc = rayOrigin - sphereCenter;
float a = rayDirection.dot(rayDirection);
float b = 2.0f * rayDirection.dot(oc);
float c = oc.dot(oc) - sphereRadius * sphereRadius;
float discriminant = b b - 4 a * c;
if (discriminant < 0) {
return false; // No intersection
} else {
return true; // Intersection detected
}
}
Explanation:
- Initialization:
rayOrigin
: Starting point of the ray.rayDirection
: Direction in which the ray extends.sphereCenter
: Center point of the sphere.sphereRadius
: Radius of the sphere.Vector Calculation:
oc
: Vector from the ray's origin to the sphere's center.oc = rayOrigin - sphereCenter
.
Coefficients Calculation:
a
: Dot product of the ray direction with itself.a = rayDirection.dot(rayDirection)
.
b
: Dot product of the ray direction withoc
, multiplied by 2.b = 2.0f * rayDirection.dot(oc)
.
c
: Dot product ofoc
with itself, subtracting the square of the sphere's radius.c = oc.dot(oc) - sphereRadius * sphereRadius
.
Discriminant:
discriminant
: Calculation of the discriminant for the quadratic equation (b^2 - 4ac
).discriminant = b b - 4 a * c
.
Intersection Check:
- If
discriminant
is less than 0, there's no intersection (returnfalse
). - Otherwise, an intersection is detected (