Intersection between a ray and a sphere

 

 

// Intersection between a ray and a sphere
// o : Ray origin
// d : Ray direction
// c : Center of sphere
// r : Radius
// t : Intersection depth
// n : Normal at intersection point
bool sphere(in vec3 o,in vec3 d,in vec3 c,in float r,out float t,out vec3 n)
{
vec3 oc = o-c;

float b=dot(d,oc);
float k = dot(oc,oc)-r*r;
t=b*b-k;

if (t<=0.0) return false;

t=-b-sqrt(t);
if (t<0.0) return false;

// Normal
n=(o+t*d-c)/r;

return true;
}

posted on 2018-01-28 21:53  fanbird2008  阅读(77)  评论(0)    收藏  举报

导航