I’m trying to detect if a line between two Vector3s intersects (or lies within) a perfect sphere.
I want to get this mathematically and I don’t really want to use a raycasts or anything similar.
Here is an quick sketch of what I’m trying to achieve:
function isLineInsideSphere(startPoint, endPoint, sphereCenter, sphereRadius)
local lineVector = endPoint - startPoint
local sphereToStart = startPoint - sphereCenter
local a = lineVector:dot(lineVector)
local b = 2 * lineVector:dot(sphereToStart)
local c = sphereToStart:dot(sphereToStart) - sphereRadius * sphereRadius
local discriminant = b * b - 4 * a * c
return discriminant >= 0
end
local startPoint = Vector3(1, 2, 3)
local endPoint = Vector3(4, 5, 6)
local sphereCenter = Vector3(2, 3, 4)
local sphereRadius = 2
local result = isLineInsideSphere(startPoint, endPoint, sphereCenter, sphereRadius)
print(result)