What does ToObjectSpace() and ToWorldSpace() do?

The wiki has a very limited explanation on this topic, I don’t think its even a sentence, so i was wondering if any of you knew what these functions were, and how they work?

37 Likes

:ToObjectSpace() converts a CFrame relative to the world relative to a specific part.
For example let’s say object A is at 0, 10, 0 and object B is at 0, 20, 0. If we ran: print(objectA.CFrame:ToObjectSpace(objectB.CFrame) it would print 0,10,0 as object A is 10 studs above object B. It’s treating object B’s CFrame as the center of the world.

:ToWorldSpace() does exactly the opposite and returns a CFrame relative to the center of the world (0, 0, 0). So if object C’s CFrame is 0, 10, 0 away from 0, 0, 0, it would return 0, 10, 0.

166 Likes

Both of those methods convert a CFrame to a specific space. World relates to the origin (0, 0, 0) axis (like when you insert parts via Roblox Studio), while object space sets it relative to the object (hence “object space”).

Using them is as simple as calling the method on a CFrame, like Part.CFrame:ToObjectSpace(). The real pain comes from operations like additives, if you aren’t well versed in CFrames (I, for one, am not at all).

Typically, everything defaults to world space unless otherwise determined by a property or scripted feature.

14 Likes

https://developer.roblox.com/articles/Understanding-CFrame

13 Likes

The CFrame of an object is relative to CFrame.new(0,0,0)*CFrame.Angles(0,0,0) (a cframe at the Origin and no rotation).

Consider the following:
I create an anchored part in workspace called MyBaseplate. This is basically a building platform for the player. For proof of concept, I want to place a part at position 5,1,5 relative to MyBaseplate. I do the following:

local baseplate = workspace.MyBaseplate
local part = workspace.Part

part.CFrame = baseplate.CFrame:ToWorldSpace( CFrame.new(5,1,5) )

This code treats baseplate.CFrame as if it was the origin for CFrame.new(5,1,5) and rotates and moves it accordingly.

Now lets say I want to save the player’s build. However whenever the player returns, he or she might not be on the same baseplate. So what I want to do is get the cframe relative to their current baseplate. For proof of concept again, I do the following code:

local baseplate = workspace.MyBaseplate
local part = workspace.Part

local cframe_to_save = baseplate.CFrame:ToObjectSpace( part.CFrame )
print(cframe_to_save)

If you run this code in order, it should do this:
image

Again if you want to used the saved cframe:

local baseplate = workspace.MyBaseplate
local part = workspace.Part

local cframe_to_save = baseplate.CFrame:ToObjectSpace( part.CFrame )

part.CFrame = baseplate.CFrame:ToWorldSpace( cframe_to_save )
3 Likes