Getting Vector3 magnitude local to a parts movement (not world-space)

So my question is this: How would I go about getting a Vector3 movement magnitude, local to its part?

Kinda having a hard time explaining it, so here’s an example:

If the part is moving to its right the Vector3 would be, for example (0,0,1), regardless of the detection it’s moving in world-space. If it was moving to its left, it would be (0,0,-1).

This is what I’ve tried:

local part =workspace.part
local Prv =part.Position

game:GetService("RunService").RenderStepped:Connect(function()
	local DirPos =part.Position -Prv
	Prv =part.Position
	
	print(DirPos.x)
end)

It gets the movement magnitude I need, but returns it in world space, not local to the part.
So moving to the parts right could be anywhere from (0,0,1) to (1,0,0.5).

I assume using CFrame somehow would be the answer, but I haven’t manage to figure it out yet. And that’s where you guys come in!

Any help or tips are greatly appreciated, I’m always looking to learn. Thanks.

1 Like

Yes, indeed, I believe you need to use CFrame. Specifically, CFrame:ToObjectSpace(). This returns the offset needed to transform from CFrame1 to CFrame2. All you need to do after is get the position from that CFrame:

local prvCFrame = CFrame.new(Prv)
local relativeChange = prvCFrame:ToObjectSpace(part.CFrame)

prvCFrame = part.Position

print(relativeChange.X, relativeChange.Y, relativeChange.Z) --get the X, Y, Z from CFrame

--remember, CFrame is not only position, but it's also orientation, so we need to get the X, Y, and Z

Ah ha! Yes, this works perfectly.

Thank you very much for your help.

1 Like