public double intersect(Ray r)
{
double t;
Vector L = r.origin.sub(pos);
double a = r.direction.dot(r.direction);
double b = 2*(r.direction.dot(L));
double c = (L.dot(L)) - (radius*radius);
double disc = b*b - 4*a*c;
if (disc < 0)
return -1;
double distSqrt = Math.sqrt(disc);
double q;
if (b < 0)
q = (-b - distSqrt)/2;
else
q = (-b + distSqrt)/2;
double t0 = q/a;
double t1 = c/q;
if (t0 > t1)
{
double temp = t0;
t0 = t1;
t1 = temp;
}
if (t1 < 0)
return -1;
if (t0 < 0)
t = t1;
else
t = t0;
return t;
}
如果没有交点,它应该返回-1。
在(5,0,0)处有一个半径为2的球。 当我以原点(0,0,0)和方向(5,0,0).unit通过一条射线时,它正确地返回3。 当我以原点(0,0,0)和方向(5,2,0).unit通过一条射线时,它正确地返回3.9。 当我以原点(0,0,0)和方向(5,0,1).unit通过一条射线时,即使射线相交,它也返回-1。 当方向是(5,0,-1).unit时,返回2.73,即使t不可能小于3,它也应该和(5,0,1).unit返回相同的结果。