How to Get the Position of a Part Relative to Another Part

Whenever I save a part’s position on a surface to a DataStore and load it, it would obviously load in the position it was saved in

But what if I wanted to load the part in another surface with the same position?

11 Likes

I believe you would do

Part.CFrame = Part.CFrame * PlayerBase.CFrame:Inverse()
1 Like

So lets say a part’s CFrame is (1,1,1) and I saved that to a DataStore, I would simply just need to do

CFrame.new(1,1,1) * Surface.CFrame ?

1 Like

To get the CFrame in object space:

local objectCFrame = part.CFrame:ToObjectSpace(otherPart.CFrame)

To convert back to world space:

local worldCFrame = part.CFrame:ToWorldSpace(objectCFrame)

More information about CFrames:

30 Likes

I’ve just changed my code as I missed something out, but yes.

2 Likes

Just for clarification, you’re loading the CFrame, and not Vector3, correct?

1 Like

Actually, the thing is I am currently saving Vector3 values, but regardless, I’m willing to make the change :slight_smile:

1 Like

How do I move the part to another surface tho?

I believe this is just to convert the CFrame values into the corresponding CFrame types.

Save the object space CFrame to the data store (or a representation of it because of data store limitations), and use CFrame:ToWorldSpace to restore it to world space.

1 Like

The part does not seem to end up in the right place


local Surface1CFrame = workspace.Target.CFrame:ToObjectSpace(workspace.Surface1.CFrame)
workspace.Target.CFrame = workspace.Surface2.CFrame:ToWorldSpace(Surface1CFrame)

You should be calling ToObjectSpace on workspace.Surface1.CFrame, as this is the new origin CFrame. You want the CFrame of Workspace.Target in the object space of Workspace.Surface1.

1 Like

So that would be

local Surface1CFrame = workspace.Surface1.CFrame:ToObjectSpace(workspace.Target.CFrame) ?

Target is the green part btw

Yes

1 Like

And if I wanted to move the part to the other surface, the code would be

workspace.Target.CFrame = workspace.Surface2.CFrame:ToWorldSpace(Surface1CFrame) ?

Yes

Hmm, it doesn’t seem to work :confused:

Could you provide more information? Could I see your code? Which part isn’t working?

1 Like

I have two Bases, I’m trying to move a part’s position on the first base to the other base.

local Part = workspace.Target
local Base1 = workspace.Surface1
local Base2 = workspace.Surface2

local CFrameFromBase1 = Base1.CFrame:ToObjectSpace(Part.CFrame)

local function MovePartToBase2()
Part.CFrame = Base2.CFrame:ToWorldSpace(CFrameFromBase1)
end

wait(5)

MovePartToBase2()

What’s not working is the part keeps on ending up in the wrong position on the second base.

1 Like

Do the two bases have the same rotation?

1 Like

Hmm, good point…

Thanks for the help @Dandystan :heart: