Camera not working properly

The problem

First up. this is no duplicate (the title is similar to other bug reports but its a different thing).
But as it says, i have a problem with setting up a camera and moving a player’s head.

I have made a LocalScript in StarterPlayerScript that looks like this:

local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local camera = workspace.CurrentCamera
local head = character:FindFirstChild("Head")
local humanoid = character:FindFirstChild("Humanoid")
local rootPart = character:FindFirstChild("HumanoidRootPart")

if not head or not humanoid or not rootPart then return end


local neck = head:FindFirstChild("Neck") or humanoid:FindFirstChild("Neck")
if not neck then
	neck = Instance.new("Motor6D")
	neck.Name = "Neck"
	neck.Part0 = character:FindFirstChild("UpperTorso") or character:FindFirstChild("Torso")
	neck.Part1 = head
	neck.Parent = head
end

local originalNeckC0 = neck.C0

game:GetService("RunService").RenderStepped:Connect(function()
	local offset = Vector3.new(0, 6, -12) 
	local targetPosition = rootPart.Position + rootPart.CFrame:VectorToWorldSpace(offset)

	camera.CameraType = Enum.CameraType.Scriptable
	camera.CFrame = CFrame.new(targetPosition) * CFrame.Angles(0, rootPart.Orientation.Y * math.pi/180, 0)

	
	local mouse = player:GetMouse()
	local direction = (mouse.Hit.p - head.Position).unit
	local angleY = math.atan2(direction.X, direction.Z)

	neck.C0 = originalNeckC0 * CFrame.Angles(0, angleY, 0)
end)

And before you ask, this script is enabled.

Current Behavior
This happens if i move fowards:

This happens if I move Backwards

and this happens if i move left/right

Excpected Behavior
It should work properly without eventual spinning.


It would be cool if someone helps me!

I’m thinking the issue lies on how you’re calculating target position for the camera. I’ve had a similar issue in the past and I fixed it by repeatedly checking player move direction and updating calculating logic appurtenant to it.

Calculate camera target normally when you’re moving forward but add a negative to the calculator when moving backwards.

A likely example to work for backwards logic would be:
-(CFrame.new(targetPosition) * CFrame.Angles(0, rootPart.Orientation.Y * math.pi/180, 0))

Please test this code snippet and tell me if it works, will modify dependedly.

using this the spinning is fixed, but the camera still moves around without focusing on the player, regardless of where he is.
I’m trying to fix it.