我正在努力在 2d 中实现一个强大的光线球相交例程。我一起破解了一个相当大的功能,因为它在 GPU 上运行,所以我无法正确调试。我的灵感来自: 圆线段碰撞检测算法? 和http://paulbourke.net/geometry/sphereline/。我不知道我应该在哪里寻找错误。我错过了一些明显的东西吗?因为我对实际的圆段碰撞感兴趣,所以我检查圆是否包围线的情况作为交叉点返回。
这是相关的代码片段:
bool CircleSegmentIntersection2d(float2 x0, float2 x1, float2 center, float r) {
float2 d = x1-x0;
float2 f = x0-center;
float a = dot2d(d,d);
float b = 2*dot2d(f,d);
float c = dot2d(f,f)-r*r;
float discriminant = b*b-4*a*c;
if( discriminant < 0 ) {
// no intersection
return false;
} else {
discriminant = sqrt(discriminant);
// either solution may be on or off the ray so need to test both
float sol1 = (-b + discriminant)/(2*a);
float sol2 = (-b - discriminant)/(2*a);
float t0 = min(sol1, sol2);
float t1 = max(sol1, sol2);
if (t1 < 0)
return false;
// Line segment doesn't intersect and on outside of sphere, in which case both values of t will either be less than 0 or greater than 1.
if (0 < t0 && 0 < t1 || t0 > 1 && t1 > 1)
return false;
// Line segment doesn't intersect and is inside sphere, in which case one value of t will be negative and the other greater than 1.
if (t0 < 0 && t1 > 1) {
return true;
}
// Line segment intersects at one point, in which case one value of t will be between 0 and 1 and the other not.
if (t0 < 0 && 0 <= t1 && t1 <= 1) {
return true;
}
// Line segment intersects at two points, in which case both values of t will be between 0 and 1.
if (0 <= t1 && t1 <= 1 && 0 <= t0 && t0 <= 1) {
return true;
}
// Line segment is tangential to the sphere, in which case both values of t will be the same and between 0 and 1.
if (length(t0-t1) < 0.005f) {
return true;
}
}
return false;
}
其中 dot2d 定义为:
float dot2d(float2 a, float2 b) {
return a.x*b.x+a.y*b.y;
}
谢谢你的时间!