Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I get the rotational velocity of the camera?

Lets say the camera moved left, I want to know how fast it was moving left and if it was moving left. How would I accomplish this?

1 answer

✓ Accepted answer

you can do this by comparing the camera's previous CFrame to its current CFrame

the simple way to do that would be something like this:

local RunService = game:GetService("RunService")

local camera = workspace.CurrentCamera
local lastOrientation = Vector3.new(camera.CFrame:ToEulerAnglesYXZ()) -- you can use a function that returns several values in an expression and it'll treat that function as those several values
-- also i'm using YXZ because that's how orientations are applied with the Orientation property
-- plus i just think it's more intuitive than xyz : 3

RunService.RenderStepped:Connect(function(delta) -- delta is the time passed since the last frame
	local orientation = Vector3.new(camera.CFrame:ToEulerAnglesYXZ())
	print("rotational velocity: ", (orientation - lastOrientation)/delta) -- the RotVelocity property is in studs per second, so you divide by the time delta to convert from studs per frame to studs per second
	lastOrientation = orientation
end)

however, this solution has one big issue, and that's the fact that if you try to go "past" 360 degrees, it just loops back to zero, making the rotational velocity absolutely massive when it really shouldn't be

what we can do instead is get the current cframe in the last cframe's object space, giving us the "difference" between those two cframes, and then convert THAT to euler angles

local RunService = game:GetService("RunService")

local camera = workspace.CurrentCamera
local lastCFrame = camera.CFrame

RunService.RenderStepped:Connect(function(delta)
	local difference = lastCFrame:ToObjectSpace(camera.CFrame)
	local velocity = Vector3.new(difference:ToEulerAnglesYXZ())/delta
	print("rotational velocity: ", velocity) 
	lastCFrame = camera.CFrame
end)

the only problem is that if you, for whatever reason, rotate the camera more than 180 degrees in a single frame, the velocity will be less than it should be, but that's practically never going to be a problem sooooo. Yah

This discussion is preserved as it was. New answers, comments, and votes are closed.