bool RaySphereIntersection(float3 ray_pos, float3 ray_dir, float3 spos, float r, float& tResult)
{
//a == 1; // because rdir must be normalized
float3 k = ray_pos - spos;
float b = dot(k,ray_dir);
float c = dot(k,k) - r*r;
float d = b*b - c;
if(d >=0)
{
float sqrtfd = sqrtf(d);
// t, a == 1
float t1 = -b + sqrtfd;
float t2 = -b - sqrtfd;
float min_t = min(t1,t2);
float max_t = max(t1,t2);
float t = (min_t >= 0) ? min_t : max_t;
tResult = t;
return (t > 0);
}
}
|