How to orient a rotation relative to the camera (or any arbitrary CFrame)

I have a script that rotates a part based on inputs from the player. T-G for pitch, F-H for yaw, and R-Y for roll.

local relativerotation = camera.CFrame:Inverse() * CurrentPart.CFrame.Rotation
connections["RenderStepped"] = RunService.RenderStepped:Connect(function(step)
		AlignOrientation.CFrame = camera.CFrame.Rotation * relativerotation
			
		local KeysInputted = UserInputService:GetKeysPressed()
		local output = {X=0, Y=0, Z=0}
		for _, keyobject in ipairs(KeysInputted) do --this handles input
			if inputkey[keyobject.KeyCode.Name] then
				local index = inputkey[keyobject.KeyCode.Name]
				output[index[1]] += index[2]
			end
		end
		relativerotation *= CFrame.fromEulerAnglesXYZ(output.Z*step*pi,-output.X*step*pi,output.Y*step*pi)
end

This script does something similar to, but not exactly what I’m looking for. This rotates the part relative to its own rotation, if that makes sense: if its rotation is rolled by 180 degrees, then the same input will rotate it in the opposite direction.

The behavior that I’m looking for is one that rotates the part relative to the camera’s orientation. No matter how the part is oriented, an input should have it rotate in the same way relative to the camera: whether its roll is 30, 45, 90, or 180 degrees, when pitched down, it should rotate in the same way.

Any help in this regard would be greatly appreciated.

2 Likes

It should be as simple as swapping the multiplier and the multiplicand. Matrix multiplication are NOT commutative, so the order matters.

relativerotation = CFrame.fromEulerAnglesXYZ(output.Z*step*pi,-output.X*step*pi,output.Y*step*pi) * relativerotation
2 Likes

Alright. I’ll give this a try, thanks.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.