Hello, I am trying to figure out a way to get the closest surface Vector3 of a part inside a specific hitbox I have created. To further elaborate:
I have a starting CFrame, let’s label it as variable origin
. From this origin
CFrame, we cast a hitbox facing forwards that extends a certain amount with a specific size and width. Using this hitbox, we can use workspace:GetPartBoundsInBox()
to get a list of all parts inside of this created hitbox, as we can set the first parameter using the origin
CFrame and we can change the size as we please. From this, we gather some new variables:

hitboxSize
= Vector3 we can customize as we please 
hitboxCenter
=origin * CFrame.new(hitboxSize.X / 2, 0, 0)
So what I am left with is these specified variables and an array of all the parts inside of the hitbox. What I am struggling with though is I want to get the closest surface POSITION, not the closest PART, to the origin
. If I wanted to get the closest part, I could just iterate through all the bounding parts and using .Magnitude from the origin
position to find the closest one, but in examples like these:
That simply wouldn’t work, as part1
's Position is way farther than part2
, but we clearly see that in terms of the hitbox, part1
is the closest. So if there was a way to find the closest surface position of part1
relative to the hitbox, it would solve this issue of parts having varying sizes.
Ideally it would get the closest surface relative to the part that’s closest to the hitbox, like this:
Orange obviously being the Vector3 returned by this function. I could have some hacky solutions like firing rays around the hitbox, but I want this to work no matter the width of the hitbox, and in edgecase scenarios where the part is too thin and doesn’t completely cover the hitbox. I know there’s some mathmetical solution to this involving cross and dot products or something that I just can’t think of right now, so any help would be appreciated. You can use the variables I set above for your solution if you’d like. Thank you.