Get a Part's Relative Position
Get a Part's Relative Position
Problem
You want to know where something is relative to where something else is.
Solution
Use the CFrame:toObjectSpace method.
Workspace.Part.CFrame:toObjectSpace(Workspace.Part2.CFrame)
Discussion
We want to find how “Part2” is positioned relative to “Part”. We use “Part” as the origin and convert the CFrame of “Part2” to be relative to the CFrame of “Part”. This leaves us with how “Part2” is relative to “Part”. What can we do with this information? We can find the distance between the two like so:
Workspace.Part.CFrame:toObjectSpace(Workspace.Part2.CFrame).p.magnitude
We use the position component of the CFrame and get its length (using the magnitude
property). Since we’re using relative positioning we are left we just how the two are related. We could also get the length between the two like so:
(Workspace.Part.Position - Workspace.Part2.position).magnitude
Using subtraction we can also get relative positioning.