Rotation relative to player

I want an object to rotate relative to the player instead of the part

right now it looks like this

I want it to rotate more like this image

Code for grab :

target.Force.Position = camera.CFrame.Position + (mouse.UnitRay.Direction * Range)

Code for rotate :

if inputObject.KeyCode == Enum.KeyCode.W then
	WKeyHeld = true
	while WKeyHeld == true and down2 == true and target ~= nil do
		target.CFrame = target.CFrame * CFrame.Angles(math.rad(2), math.rad(0), math.rad(0))
		wait()
	end
end

You’ll want a combination of CFrame.fromAxisAngle to rotate around a given Vector3, and VectorToObjectSpace to get vectors relative to the part you want to rotate. I think it makes most sense to rotate around the Camera’s RightVector, but just use the world-space Up vector. Here’s an example script that shows how it could work:


local RunS = game:GetService("RunService")
local InputS = game:GetService("UserInputService")

local camera = game.Workspace.CurrentCamera
local grabbedPart = game.Workspace.Part

local V_RIGHT =  Vector3.FromNormalId(Enum.NormalId.Right)
local V_LEFT =  Vector3.FromNormalId(Enum.NormalId.Left)
local V_UP =  Vector3.FromNormalId(Enum.NormalId.Top)
local V_DOWN =  Vector3.FromNormalId(Enum.NormalId.Bottom)

InputS.InputBegan:Connect(function(input)
	local keyCode = input.KeyCode

	local rotateDir
	if keyCode == Enum.KeyCode.W then
		rotateDir = V_RIGHT
	elseif keyCode == Enum.KeyCode.S then
		rotateDir = V_LEFT
	elseif keyCode == Enum.KeyCode.A then
		rotateDir = V_UP
	elseif keyCode == Enum.KeyCode.D then
		rotateDir = V_DOWN
	end

	if rotateDir then
		local rsConnection
		rsConnection = RunS.RenderStepped:Connect(function(dt)
			--Calculate amount to rotate by this frame
			local rotation = CFrame.new()
			local camRight = camera.CFrame.RightVector
			rotation *= CFrame.fromAxisAngle( grabbedPart.CFrame:VectorToObjectSpace( camRight ), -rotateDir.X * dt )
			rotation *= CFrame.fromAxisAngle( grabbedPart.CFrame:VectorToObjectSpace( V_UP ), -rotateDir.Y * dt )
			
			--Apply calculated rotation
			grabbedPart.CFrame *= rotation
		end)

		InputS.InputEnded:Connect(function(_input)
			if _input == input then
				rsConnection:Disconnect()
			end
		end)
	end
end)

Put the code in a LocalScript inside StarterPlayerScripts, and call it “ControlScript”. That way it overrides the default controls so you can test rotating the part with WASD without walking.

Let me know if you’ve any questions or you need it to work in a different way :slight_smile:

1 Like

I just woke up, I will test this out right now

1 Like

I modified it a little , but bro ur using operators I didn’t even know existed. U a genius or sum? Thank you for bestowing me with ur insane intelligence