0
\$\begingroup\$

The discriminant is not working. This code produces incorrect distances from ray to sphere, but it can tell whether or not the ray does strike the sphere.

HOW HARD IS THIS I'VE BEEN TRYING TO DO THIS FOR 2 DAYS

float raySphereIntersect2(glm::vec3 ray, glm::vec3 origin, glm::vec3 sphere_origin, float sphere_radius, float drawdistance){
    //A sphere is given by its center
    float cx = sphere_origin.x;
    float cy = sphere_origin.y;
    float cz = sphere_origin.z;
    //its radius R
    float R = sphere_radius;
    //and its color
        //Ignored
    //A line segment (ray) is given by its endpoints:
    //P0
    float x0 = origin.x;
    float y0 = origin.y;
    float z0 = origin.z;
    //and P1
    float x1 = origin.x+(ray * drawdistance).x;
    float y1 = origin.y+(ray * drawdistance).y;
    float z1 = origin.z+(ray * drawdistance).z;
    //set
        float dx = x1 - x0;
        float dy = y1 - y0;
        float dz = z1 - z0;

        float a = dx*dx + dy*dy + dz*dz;
        float b = 2*dx*(x0-cx) + 2*dy*(y0-cy) + 2*dz*(z0-cz);
        float c = cx*cx + cy*cy + cz*cz + x0*x0 + y0*y0 + z0*z0 + -2*(cx*x0 + cy*y0 + cz*z0) - R*R;

        float discriminant = (b * b) - (4 * a * c);
        if (discriminant < 0)
            return -1;
        // OK so there is a solution, compute the distance
        float t = (-b - sqrtf(discriminant))/(2*a);
        return t;
}
\$\endgroup\$
  • \$\begingroup\$ You are computing t such that (origin + t(dx,dy,dz)) lies on the sphere. That means the distance from origin is $t*sqrt(dx*dx+dy*dy+dz*dz)$. btw if you used glm's matrix operations such as dot product rather than operating on coordinates, the code would be easier to read IMO. \$\endgroup\$ – stewbasic Sep 6 '18 at 3:39
  • \$\begingroup\$ Thank you, although it's a bit late. I ended up using glm::gtx::raySphereIntersect \$\endgroup\$ – Geklmintendon't of Awesome Sep 8 '18 at 1:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.