Model not rotating properly

I’m currently working on a shooting turret which is supposed to rotate with the camera movement. But the whole model should only move left and right while the gun itself moves only up and down. I should be able to achieve this by setting the rotation of the whole model to look at the mouse position coordinates except on the Y axis and the rotation of the gun to the same but just the Y axis.

game["Run Service"].RenderStepped:Connect(function()
	local turretPivot = turret:GetPivot()
	local gunPosition = turret.gun:GetPivot()
	local angle = CFrame.lookAt(gunPosition.p, Vector3.new(gunPosition.p.X, mouse.Hit.Y, gunPosition.p.Z))
	turret.gun:PivotTo(angle)
	turret:PivotTo(CFrame.lookAt(turretPivot.Position, Vector3.new(mouse.Hit.Position.X,turretPivot.Position.Y,mouse.Hit.Position.Z)))
end)

But when I do that, the position its trying to look at is too close to the origin so it doesn’t work.


What I have done is set the gun rotation to all the axis but that doesn’t give the desired result.

game["Run Service"].RenderStepped:Connect(function()
	local turretPivot = turret:GetPivot()
	local gunPosition = turret.gun:GetPivot()
	local angle = CFrame.lookAt(gunPosition.p, mouse.Hit.Position)
	turret.gun:PivotTo(angle)
	turret:PivotTo(CFrame.lookAt(turretPivot.Position, Vector3.new(mouse.Hit.Position.X,turretPivot.Position.Y,mouse.Hit.Position.Z)))
end)

What am I missing? I’m still pretty confused by CFrame sometimes so I’m sorry if this is trivial.

Maybe try clamping values of the CFrame so that they aren’t too far up or down?

Could you show me how I can do that?

Basically it’s the clamp function.

clamp(x: number, min: number, max: number): number

Returns a number between [min, max].

Here’s some practical code:

local function clampCFrame(cf)
    local pos = cf.Position
    local clampedY = math.clamp(pos.Y, 10, 100) -- clamp the Y component between 10 and 100
    return CFrame.new(Vector3.new(pos.X, clampedY, pos.Z), cf.LookVector)
end

Thanks for your response! But I think the problem is that the Y value of mouse.Hit.Position doesn’t actually change while looking at the baseplate for example so clamping the value down didn’t fix the issue unless I implemented it incorrectly maybe?
CFrame.lookAt(gunPosition.p, Vector3.new(gunPosition.p.X,math.clamp(mouse.Hit.Position.Y, -1,1), gunPosition.p.Z))