我正在尝试为我的raytracer查找线和球之间的交点。到目前为止,我的工作正常,但是z交叉点的返回值为15,这对半径为1的球体不利。 new_origin
是射线与球体的交点。 new_direction
是该交叉点的法线。显然new_origin
计算错误。
[origin
和direction
是射线(线)的原点和方向。
我的代码:
bool Sphere::intersection(const glm::vec3 &origin, const glm::vec3 &direction, glm::vec3 &new_origin, glm::vec3 &new_direction)
{
//
// See this for explantion of the formula: https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
//
glm::vec3 trans_origin = origin - this->origin;
float a = glm::dot(direction, direction);
float b = 2 * glm::dot(trans_origin, direction);
float c = glm::dot(trans_origin, trans_origin) - this->radius * this->radius;
float discriminant = b * b - 4 * a * c;
if (discriminant < 0.f) return false;
float depth = (-b + sqrtf(discriminant)) / 2 * a;
float t = (-b - sqrtf(discriminant)) / 2 * a;
if(t < depth) {
depth = t;
}
new_origin = origin + depth * direction;
new_direction = glm::normalize(trans_origin + depth * direction);
return true;
}
3Dave在其评论中已经指出了其中一个问题(操作员的优势)>
(-b + sqrtf(discriminant)) / 2 * a
不正确。应该是(-b + sqrtf(discriminant)) / (2 * a)
。