# Finding the closest Vector3 point on a part from the character

Essentially, what I’m trying to achieve is finding the closest possible Vector3 position of a part from the character. These parts can range in different sizes and rotations.

• Doing a simple raycast `Ray.new(origin, direction)` would produce the Red Arrow, I need the closest point.
• Raycasting the front of the character will mean I will have to face the part in order for it to work.

I’m not the best when it comes to math. Any help with solving this predicament would be greatly appreciated!

6 Likes

This is the textbook case of vector projection being useful.

3 Likes

The best way to do this is to transform your reference point on the character (e.g. the position of the RootPart) into the local space of the part, then do a simple closest point on AABB check by clamping the position according to the part’s size, and finally transform it back into world space. Here’s some code:

``````local function ClosestPointOnPart(Part, Point)
local Transform = Part.CFrame:pointToObjectSpace(Point) -- Transform into local space
local HalfSize = Part.Size * 0.5
return Part.CFrame * Vector3.new( -- Clamp & transform into world space
math.clamp(Transform.x, -HalfSize.x, HalfSize.x),
math.clamp(Transform.y, -HalfSize.y, HalfSize.y),
math.clamp(Transform.z, -HalfSize.z, HalfSize.z)
)
end
``````
52 Likes

Everyone note: This doesn’t account for if the point is inside of the part.