Advertisement

Ray-Sphere intersection explanation

Started by August 22, 2019 12:01 AM
1 comment, last by Gaius Baltar 5 years, 3 months ago

Hey there,

I recently came across this: https://github.com/ssloy/tinyraytracer

It's a raytracer implemented in a very minimal way.

This person uses a method to find intersections between a ray and a sphere that I can't understand. His implementation is as follows:


bool ray_intersect(const Vec3f &orig, const Vec3f &dir, float &t0) const {
        Vec3f L = center - orig;
        float tca = L*dir;
        float d2 = L*L - tca*tca;
        if (d2 > radius*radius) return false;
        float thc = sqrtf(radius*radius - d2);
        t0       = tca - thc;
        float t1 = tca + thc;
        if (t0 < 0) t0 = t1;
        if (t0 < 0) return false;
        return true;
    }

This code confuses me, because I've always used the quadratic formula to get the discriminant of the ray-sphere function. It looks like he is doing the same thing, but perhaps using a different formula to begin with?

If someone has the time I'd appreciate an explanation or a breakdown of this method.

I found a great site that goes in-depth about how this method works: 

https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-sphere-intersection

Solved my problem.

This topic is closed to new replies.

Advertisement