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; }