Move a part to the closest point of another part

Hi guys, I have no idea how to solve this problem so I decided to ask here. I hope I can explain it properly…

(Image attached)
I am trying to get Part A to move to the “closest point” of part B, represented by the blue line.


I have some basic knowledge on CFrames, but I have absolutely no idea how to do this.
I thought of using rays but it would have to use the same “closest point” im trying to get for the orientation.

I want the end result to be like this:
img1
Does anyone know how to achieve this? Thanks in advance.

Do you know any tutorials on cross product? I am clueless

You may not find cross product tutorials specific to Roblox, but coding is math, so try to understand vector/matrix dot products and such (as Vector3’s are just 3D vectors and CFrames are 4x4 matrices) and use your knowledge to find applications.

I really recommend 3Blue1Brown’s essence of linear algebra series. I am still learning myself.

I think I have a solution, but you need to be able to define which axis of PartB it snaps to, and how PartA should orient relative to PartB. Here I just use PartB’s Z Axis, and make it so that PartA has the same CFrame as PartB but offset.

local partA = blablabla
local partB = blablabla

local objectSpaceA = partB.CFrame:PointToObjectSpace(partA.Position) --This is how far away partA is from partBs perspective
objectSpaceA = Vector3.new(0,0, objectSpaceA.Z) --By removing the X and Y components, the part is now only able to move along the Z axis of partB
partA.CFrame = partB.CFrame + partB.CFrame:VectorToWorldSpace(objectSpaceA) --Sets partA to the same CFrame as partB, then moves partA to the correct offset
4 Likes

Thank you so much man, it worked! (I had to change Z to X though but eyy)

1 Like