How to detect if a line between two Vector3s intersects a sphere

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:

I would appreciate any help or tips!

1 Like
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)

Had to make up the values … best guess.

2 Likes

Currently I don’t have access to studio but I’ll try this later and see whether it works. Thanks!

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.