Camera Lock-On-Player flicker issue

I made a simple script to change a local player’s camera to look at another player, such as a camera lock on mechanic. But I’m currently dealing with this problem when a player gets too close to the person they are looking at (For example on top of them) the camera tends to flicker or flip on top. I understand why it is happening but am not sure on how to fix it. I tried offsets or locking the camera Y position, but the issue still occurred, just in different places. Does anyone know how I can fix this?

Here is the code I used to lock on:

local X = 12
local Focused = false

game:GetService("UserInputService").InputBegan:Connect(function(inp, processed)
	local player = game.Players.LocalPlayer
	local char = player.Character
	local Cam = game.Workspace.CurrentCamera
	local mouse = player:GetMouse()
	local run = game:GetService("RunService")

	if inp.KeyCode == Enum.KeyCode.E and not processed and not Focused then
		Cam.CameraType = "Scriptable"
		Focused = true
		local XOffset = 0
		local YOffset = char.HumanoidRootPart.Position.Y + 3
		local ZOffset = 0
		local lockTo = GetClosestPlayer()[2].HumanoidRootPart.Position
			while Focused do

				local CFrameOffset = - Cam.CFrame:ToObjectSpace(char.HumanoidRootPart.CFrame).X)  + XOffset, YOffset, (Cam.CFrame:ToObjectSpace(char.HumanoidRootPart.CFrame).Z - Cam.CFrame:ToObjectSpace(char.HumanoidRootPart.CFrame).Z))
				local Offset =,3,0)
				local A = char.HumanoidRootPart.Position
				local B = lockTo

				local distance = (B-A).magnitude
				local V = B + ((A + Offset) - B).Unit * ((A - B).Magnitude + X)
				Cam.CFrame =, A)
				print("Camera is", (Camera.CFrame.Position.Y - B.Y), "studs vertically from target")
				local plr = game.Players.LocalPlayer.Character.HumanoidRootPart.Position
				local lookAt =, plr.Y, lockTo.Z)
				local newCframe =, lookAt)
				game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = newCframe
	elseif inp.KeyCode == Enum.KeyCode.E and not processed and Focused then
		Focused = false
		Cam.CameraType = "Custom"

Here is the camera issue in action:

1 Like