Preview:
//--intersection function--
IntersectionResult sphere::IntersectTest(ray _ray)
{
    //creating values
    IntersectionResult testResult;
    testResult.hitsphere = false;

    //p - a calucation for easier use in next calculations
    glm::vec3 delta = sphereCenter - _ray.origin;

    //calculating d
    float d = glm::length(delta - glm::dot(delta,_ray.dir) * _ray.dir);

    //--calculate intersection point--

    //calculating x
    float intersectx = glm::sqrt((radius * radius) - (d * d));

    //final intersect point calculation
    glm::vec3 Intersect_Point = _ray.origin + (glm::dot((sphereCenter - _ray.origin), _ray.dir) - intersectx) * _ray.dir;
    
    //main intersection test
    //if the ray is less than the radius of the sphere that means it hit so set hit to true
    if (d <= radius)
    {
        testResult.Intersectpoint = Intersect_Point;
        testResult.hitsphere = true;
    }

    //returns the result of the ray
    return testResult;
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter