Finding closest point between a sphere and a polygon

This was more of a personal issue, as my games involve a lot of projectiles. I wanted to make a system where I could, by knowing a sphere’s center and another random shape’s center, or their positions persay, to be able to find their exact point of intersection in the 3D roblox environment.

image

image

Finding this point in paper would be quite easy, simple trigonometry on a plane. I came up with a quicker solution for other developers who had trouble with this same issue to enjoy.

image

By grabbing the normal vector from a raycast between the sphere and the random shape, we are able to find the normal vector of its surface. From there, we can invert it (simplest way would be by multiplying it by -1) and create a new raycast. This second raycast will have its origin on the center of our sphere.

image

The intersection point between this second raycast will be our closest point of intersection between the sphere and the selected shape.

I’m aware that this is a very specific resource for a very specific problem, but I’ve seen many searches on this topic by other developers and decided to share my solution that doesn’t involve complicated trigonometry.

local Sphere = workspace.Sphere
local Shape = workspace.Shape

local p, pp, normal = workspace:Raycast(Shape.Position, (Part.Position-Sphere.Position), Params)
-- Make Params ignore Sphere of course

local invertedNormal = normal * -1

local p, DesiredIntersection, n = workspace:Raycast(Shape.Position, (invertedNormal * SphereRadius+0.1), Params)
-- We add 0.1 or a lower value >0 so the ray is just enough to detect the intersection

--The DesiredIntersection variable is the intersection between both shapes.
11 Likes