gpt4 book ai didi

c++ - 平面和球体光线追踪的交集

转载 作者:行者123 更新时间:2023-12-02 10:37:54 24 4
gpt4 key购买 nike

我试图为我的光线追踪器找到一条线和一个球体之间的交点。到目前为止我所做的工作,但是返回 15 的 z 交点,这对于半径为 1 的球体不利。我做错了什么。 new_origin是射线与球体的交点。 new_direction是那个路口的法线。显然 new_origin计算错误。
origindirection是射线(线)的原点和方向。

我的代码:

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 is incorrect. Should be (-b + sqrtf(discriminant)) / (2 * a).



另一个后来,选择较小的交叉点。
if (t < depth) {
depth = t;
}

假设一条射线有一个原点和一个方向,即使你找到两个交点,球体也可能在相反的方向上,或者射线的原点可能在球体内。

您需要的是 下正解决方案。

另一个可能的问题是关于 new_direction ,但我并不完全清楚你在考虑哪个“正常”。

关于c++ - 平面和球体光线追踪的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59428617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com