Certainly! Here's a C++ function that accomplishes the task:
#include <cmath>
struct Point {
float x, y, z;
};
bool closestPointOnSegmentToSphere(const Point& segmentStart, const Point& segmentEnd,
const Point& sphereCenter, float sphereRadius,
Point& closestPoint) {
// Calculate the direction vector of the segment
float segmentDirectionX = segmentEnd.x - segmentStart.x;
float segmentDirectionY = segmentEnd.y - segmentStart.y;
float segmentDirectionZ = segmentEnd.z - segmentStart.z;
// Calculate the vector from the start of the segment to the sphere center
float startToSphereX = sphereCenter.x - segmentStart.x;
float startToSphereY = sphereCenter.y - segmentStart.y;
float startToSphereZ = sphereCenter.z - segmentStart.z;
// Calculate the parameterized value of the closest point on the segment to the sphere center
float t = (startToSphereX * segmentDirectionX + startToSphereY * segmentDirectionY + startToSphereZ * segmentDirectionZ) /
(segmentDirectionX * segmentDirectionX + segmentDirectionY * segmentDirectionY + segmentDirectionZ * segmentDirectionZ);
// Clamp the parameterized value to the segment bounds
t = fmaxf(0.0f, fminf(1.0f, t));
// Calculate the closest point on the segment to the sphere center
closestPoint.x = segmentStart.x + t * segmentDirectionX;
closestPoint.y = segmentStart.y + t * segmentDirectionY;
closestPoint.z = segmentStart.z + t * segmentDirectionZ;
// Calculate the distance between the closest point and the sphere center
float distance = sqrtf(powf(closestPoint.x - sphereCenter.x, 2) +
powf(closestPoint.y - sphereCenter.y, 2) +
powf(closestPoint.z - sphereCenter.z, 2));
// Check for collision
if (distance <= sphereRadius) {
// Calculate the collision point closest to the start of the segment
closestPoint.x = segmentStart.x + t * segmentDirectionX - sphereRadius * (closestPoint.x - sphereCenter.x) / distance;
closestPoint.y = segmentStart.y + t * segmentDirectionY - sphereRadius * (closestPoint.y - sphereCenter.y) / distance;
closestPoint.z = segmentStart.z + t * segmentDirectionZ - sphereRadius * (closestPoint.z - sphereCenter.z) / distance;
return true; // Collision detected
} else {
return false; // No collision
}
}