Clamping CFrame and looking at a target

Hello! Right now this clamps the rotation on the x axis. I’m looking to add a feature and I’m lost on how to do it. I would like to make “Part” look at “Target” but still clamp the CFrame.

local RunService = game:GetService('RunService')

local Part = workspace.Part
local Target = workspace.Target 

RunService.Stepped:Connect(function()
	local x,y,z = Part.CFrame:ToOrientation()
	
	local xClamp = math.clamp(math.deg(x), -45, 45)
	
	Part.CFrame = CFrame.new(Part.CFrame.p) * CFrame.fromOrientation(math.rad(xClamp),0,0)
end)

Hah thanks bronsonman but now I’m trying to find a clamping method.

I am not the best at using this, but I believe you could use Raycasting too.

I’ll bite. So, you can do something like this:

local RunService = game:GetService('RunService')

local Part = workspace.Part
local Target = workspace.Target

local x = Part.CFrame:ToEulerAnglesXYZ()
RunService.Stepped:Connect(function()
	local _, y, z = Part.CFrame:ToEulerAnglesXYZ()
	
	local xClamp = math.clamp(math.deg(x), x - 45, x + 45) -- aka 45 degrees
	
	Part.CFrame = CFrame.new(Part.CFrame.Position) * CFrame.fromEulerAnglesXYZ(math.rad(xClamp), y, z)
end)

You should get something like this!

2 Likes