Camera jumps from sides to sides

So, Im making a 2d fighting game in 3d space where you still can move to sides. And so I have problems with camera. It’s X position value jumps so high that its comes to another side which isn’t really cool. How would I fix that?

Here the code:
--Character
local plr = game.Players.LocalPlayer
local char: Model = plr.Character or plr.CharacterAdded:Wait()
local hrp: BasePart = char:WaitForChild('HumanoidRootPart')
local hum: Humanoid = char:WaitForChild("Humanoid")

--Services
local rs = game:GetService("RunService")
local info = require(game.ReplicatedStorage.Modules.Info)

--Enemy Character
local enemy: Model = info.Enemy
local ehrp: BasePart = enemy.HumanoidRootPart
local ehum: Humanoid = enemy.Humanoid

--Values
local camera = workspace.CurrentCamera

--Functions
local p1 = Instance.new("Part") --Represents a camera
p1.Anchored = true
p1.CanCollide = false
p1.Size = Vector3.new(1,1,1)
p1.Color = Color3.new(1,0,0)
p1.Parent = workspace

rs.RenderStepped:Connect(function()
	hrp.CFrame = CFrame.new(hrp.Position,Vector3.new(ehrp.Position.X,hrp.Position.Y,ehrp.Position.Z))
	
	local x,y,z = 0,0,0
	x = (hrp.Position.X+ehrp.Position.X)/2
	y = hrp.Position.Y+2
	z = (hrp.Position.Z+ehrp.Position.Z)/2
	
	local pos = Vector3.new(x,y,z)
	local middlePoint = CFrame.new(pos,hrp.Position+Vector3.new(0,2,0))
	
	local ZOffset = 20
	ZOffset = (hrp.Position.X-ehrp.Position.X)/2
	if ehrp.Position.X > hrp.Position.X then
		ZOffset = (ehrp.Position.X-hrp.Position.X)/2
		if ZOffset < -20 then
			ZOffset = -20
		elseif ZOffset > -10 then
			ZOffset = -10
		end
	else
		if ZOffset > 20 then
			ZOffset = 20
		elseif ZOffset < 10 then
			ZOffset = 10
		end
	end
	
	local pos2 = middlePoint*CFrame.new(ZOffset,0,0)
	local endPos = CFrame.new(pos2.Position,pos)
	
	camera.CFrame = endPos
	p1.CFrame = endPos
end)
And here the demo: