Collision problem for the custom camera

Hello developers!

I did a collision for the camera, but for some reason that I don’t understand, the raycast does not work correctly for the task assigned to it. Can you tell me what to do so that the camera does not pass through objects? Here is my current script:

local RunService = game:GetService("RunService")
local Context = game:GetService("ContextActionService")
local Player = game:GetService("Players").LocalPlayer
local Camera = workspace.CurrentCamera
local YAngle = 0
local XAngle = 0
Camera.CameraType = Enum.CameraType.Custom
Context:BindAction("CameraMovement", function(_, _, input)
	XAngle = XAngle - input.Delta.X * 0.4
	YAngle = math.clamp(YAngle - input.Delta.Y * 0.4, -80, 80)
end, false, Enum.UserInputType.MouseMovement)
RunService.RenderStepped:Connect(function()
	local Character = Player.Character or Player.CharacterAdded:Wait()
	if Character:FindFirstChild("HumanoidRootPart") then
		local CameraPosition = Vector3.new(0, 0, 7)
		local RootPart = Character:FindFirstChild("HumanoidRootPart")
		local Origin = RootPart.Position
		local Direction = CFrame.lookAt(Origin, Camera.CFrame.Position).LookVector * CameraPosition.Z
		local raycast = Ray.new(Origin, Direction)
		local hit, hitPosition = workspace:FindPartOnRayWithIgnoreList(raycast, {workspace.Map.IgnoreListForCamera})
		if hit then
			print(hit)
			local Magnitude = (hitPosition - Origin)
			local VectorZ = Magnitude.Magnitude
			CameraPosition = Vector3.new(CameraPosition.X, CameraPosition.Y, VectorZ)
		end
		if Character and RootPart then
			local StartCFrame = CFrame.new((RootPart.CFrame.p + Vector3.new(0, 2, 0))) * CFrame.Angles(0, math.rad(XAngle), 0) * CFrame.Angles(math.rad(YAngle), 0, 0)
			local CameraCFrame = StartCFrame + StartCFrame:VectorToWorldSpace(Vector3.new(CameraPosition.X, CameraPosition.Y, CameraPosition.Z))
			local CameraFocus = StartCFrame + StartCFrame:VectorToWorldSpace(Vector3.new(CameraPosition.X, CameraPosition.Y, -500000))
			Camera.CFrame = CFrame.new(CameraCFrame.p, CameraFocus.p)
		end
	end
end)

This script is supposed to prevent the camera from passing through objects, but this happens:
Here is an ordinary wall…


When I try to swipe the camera through an object about below the 0th degree, everything is fine…

That’s the way it’s meant to be, but if I raise the degree HIGHER than 0, something happens that I can’t explain in any way…

The camera just enters the object… I tried to fix it for about a week with various methods, but all attempts were in vain. I do not know why this is happening and how to fix it. Could you please tell me how to fix it?

Have you tried to change it to Enum.CameraType.Scriptable? Or is there another script does that?

Yes, but it disables camera rotation
This system is built on top of the standard roblox camera system.