Simplifying the Ray-Sphere Intersection

This commit is contained in:
Armin Friedl 2022-07-25 19:18:28 +02:00
parent ba40f3736c
commit 0d7a04c58d

View file

@ -7,14 +7,14 @@
double hit_sphere(const point3 &center, double radius, const ray &r) {
vec3 oc = r.origin() - center;
auto a = dot(r.direction(), r.direction());
auto b = 2.0 * dot(oc, r.direction());
auto c = dot(oc, oc) - radius * radius;
auto discriminant = b * b - 4 * a * c;
auto a = r.direction().length_squared();
auto half_b = dot(oc, r.direction());
auto c = oc.length_squared() - radius * radius;
auto discriminant = half_b * half_b - a * c;
if (discriminant < 0) {
return -1.0;
} else {
return (-b - sqrt(discriminant)) / (2.0*a);
return (-half_b - sqrt(discriminant)) / a;
}
}