射线与球体相交检测
原理:参照实时碰撞检测算法技术上的原理;但书上的实现有问题。重新实现如下:
C++实现:
static bool getRaySphereIntersect(vector3d rayOrigin, vector3d rayDir, vector3d sphereCenter, float sphereRadius, std::vector<vector3d> &intersectPoint) { vector3d v = rayOrigin - sphereCenter; float b = 2.0f * rayDir.dotProduct(v); float c = v.dotProduct(v) - sphereRadius * sphereRadius; float discriminant = (b * b) - (4.0f * c); if (discriminant < 0.0f)return false; discriminant = sqrt(discriminant); float far = (-b + discriminant) / 2.0f; float near = (-b - discriminant) / 2.0f; vector3d intersectFarPoint = rayOrigin + rayDir*far; vector3d intersectNearPoint = rayOrigin + rayDir*near; bool res = (far >= 0.0f || near >= 0.0f); if (res) { if (near > 0 )intersectPoint.push_back(intersectNearPoint); if (far > 0)intersectPoint.push_back(intersectFarPoint); } return res; }