Certainly! Below is a C++ function that calculates the closest point on a segment to the surface of a sphere, and if there's a collision, it returns the first collision point. For simplicity, I'm assuming you have a 3D vector class named Vec3 with basic operations such as addition, subtraction, dot product, and scalar multiplication already defined. If not, you will need to implement these operations for the function to work.
#include <cmath>
class Vec3 {
// Assume Vec3 has the following members and methods:
// float x, y, z;
// Vec3(float x, float y, float z);
// Vec3 operator+(const Vec3& rhs) const;
// Vec3 operator-(const Vec3& rhs) const;
// Vec3 operator*(float scalar) const;
// float dot(const Vec3& rhs) const;
// float length() const;
// Vec3 normalize() const;
};
bool findClosestPointOnSegmentToSphere(
const Vec3 &segmentStart,
const Vec3 &segmentEnd,
const Vec3 &sphereCenter,
float sphereRadius,
Vec3 &closestPoint)
{
Vec3 segmentDirection = segmentEnd - segmentStart;
Vec3 startToCenter = sphereCenter - segmentStart;
float segmentLength = segmentDirection.length();
// Normalize the segment direction
segmentDirection = segmentDirection * (1.0f / segmentLength);
// Find the projection of the sphere's center onto the segment
float projectionLength = startToCenter.dot(segmentDirection);
Vec3 closestPointOnInfiniteLine = segmentStart + segmentDirection * projectionLength;
// Check if the projection is within the segment
if (projectionLength < 0.0f) {
// Closest point is the segment start
closestPoint = segmentStart;
} else if (projectionLength > segmentLength) {
// Closest point is the segment end
closestPoint = segmentEnd;
} else {
// Closest point is within the segment
closestPoint = closestPointOnInfiniteLine;
}
// Calculate the distance from the sphere's center to the closest point on the segment
float distanceToSphereCenter = (closestPoint - sphereCenter).length();
// Check if there is a collision
if (distanceToSphereCenter < sphereRadius) {
// Calculate the collision point
float distanceFromClosestPointToCollision = std::sqrt(sphereRadius * sphereRadius - distanceToSphereCenter * distanceToSphereCenter);
closestPoint = closestPointOnInfiniteLine - segmentDirection * distanceFromClosestPointToCollision;
return true;
}
return false;
}
This function assumes that the Vec3 class has a constructor that takes three floats for the x, y, and z coordinates, as well as member functions for vector addition, subtraction, dot product, length calculation, and normalization.
To use this function, create Vec3 objects for the start and end of the segment and for the center of the sphere, then call findClosestPointOnSegmentToSphere() with a Vec3 reference for the closestPoint parameter. The function will modify closestPoint to be the closest point on the segment to the sphere surface and will return true if there is a collision, otherwise false.