How do I limit the camera to prevent rapid spinning when aiming down?

Hello, I’ve made a simple segment of code that checks for a part, and if it is the case. Then it sets the camera POV to that. However, if I play the game and go under the part thats set. The camera begins to rapidly spin and do 180s and more. How can I prevent that from happening and just make it aim down naturally with no issues?

My Code:

-- yes i know this looks bad so I am up for any ideas on how to rewrite this.
task.spawn(function()
	while task.wait() do
		if LockedViewOn then
			local TargetCFrame = CFrame.new(LockedViewOn.Position, ServPlayers.LocalPlayer.Character.PrimaryPart.Position)
			Camera.CFrame = TargetCFrame
		end
	end
end)
1 Like

This should work for you

task.spawn(function()
	while task.wait() do
		if LockedViewOn then
			local playerPos = LocalPlayer.Character.PrimaryPart.Position
			local cameraPos = LockedViewOn.Position

			local targetCFrame = CFrame.lookAt(cameraPos, playerPos, Vector3.yAxis)
			Camera.CFrame = targetCFrame
		end
	end
end)

Going to the middle, below the camera part. The camera starts to tweak out still. The code works fine though, it’s just that I’m unsure on how to prevent the sudden 180s.

Possibly clamping would help.

if LockedViewOn then
    local playerPos = ServPlayers.LocalPlayer.Character.PrimaryPart.Position
    local camPos = LockedViewOn.Position
    local dir = (playerPos - camPos).Unit
    local clampedDir = Vector3.new(dir.X, math.clamp(dir.Y, -0.99, 0.99), dir.Z)
    local targetCFrame = CFrame.new(camPos, camPos + clampedDir)
    Camera.CFrame = Camera.CFrame:Lerp(targetCFrame, 0.1)
end
1 Like

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