Need help with limiting how far camera goes in first person

Hi everyone,

I’m making a script that handles first person camera movement, but I need help getting the horizontal camera rotation limited. This is what I want:

  • I wanna limit how far the camera goes horizontally (left right) in first person, so that the limit is 90 degrees from the characters look vector.
  • But I just can’t get it to be limited.
  • I tried using AI but that didn’t help because AI is stupid.

This is my script:

local PlayerCharacter = script.Parent
local CharacterHead = PlayerCharacter:WaitForChild("Head")
local GameWorkspace = game:GetService("Workspace")
local PlayerCamera = GameWorkspace.CurrentCamera
local RunningService = game:GetService("RunService")

RunningService.RenderStepped:Connect(function()
	for LoopingPlace, CharacterDescendant in pairs(PlayerCharacter:GetChildren()) do
		if (CharacterDescendant:IsA("BasePart") or CharacterDescendant:IsA("MeshPart")) and CharacterDescendant ~= CharacterHead then
			CharacterDescendant.LocalTransparencyModifier = 0
		end
	end
	if CharacterHead.LocalTransparencyModifier >= 1 then -- focus on this if-statement, this is where the camera is handled
		local CharacterHeadPosition = CharacterHead.CFrame.Position
		local PlayerCameraRotation = PlayerCamera.CFrame - PlayerCamera.CFrame.Position
		local CameraWorldOffset = PlayerCameraRotation:VectorToWorldSpace(Vector3.new(0, 1.25, -1))
		PlayerCamera.CFrame = CFrame.new(CharacterHeadPosition + CameraWorldOffset) * PlayerCameraRotation
	end
end)

Why do I wanna limit the camera?

If I don’t limit how far the camera can go horizontally in first person I can move the camera to face the back precisely, which is uncanny since a real person like us can also not rotate their head to their back, or else their neck will break, which is not good…

I’m looking for a real solution, not a workaround like removing first person or making the character move along with the head (since a normal person doesn’t also move their entire body around when moving their head, or else they’ll fall over).

I hope you can come up with a solution, thanks!

Could you not just work out the camera angle using Vector3.Dot() then if the angle is greater than 90 degrees, set the camera angle to 90 degrees?

Information about the dot product can be found here.

I’ll try that soon when I have free time, thanks.

edit: what you said solved my problem, thanks.

1 Like

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