How would i make his head not turn 360 degrees

So I have an NPC who is supposed to look at you but can’t get his head to stay constrained to an area where he can’t turn his head 360 degrees.
This is the code

function findTorso(pos)
	local torso = nil
	local dist = 30
	local child = workspace:children()
	for i=1, #child do
		if child[i].className == "Model" then
			local h = child[i]:findFirstChild("Humanoid")
			if h ~= nil then
				local check = child[i]:findFirstChild("Head")
				if check ~= nil then
					if (check. Position - pos).magnitude < dist then
						torso = check
						dist = (check. Position - pos).magnitude
					end
				end
			end
		end
	end
	return torso
end

while true do
	wait()
	local torso = findTorso(script.Parent.Position)
	if torso ~= nil then
		script.Parent.CFrame = CFrame.new(script.Parent.Position, torso.Position)
	end
end

But where in your code are you even turning the head, maybe show a video?

Try this out:


local head = script.Parent.Head -- Adjust this path as needed
local maxAngle = math.rad(45) -- Maximum angle in radians
local originalCFrame = head.CFrame
local originalDirection = (originalCFrame.LookVector).unit

-- Function to clamp the head rotation
local function clampHeadRotation(targetPosition)
    local headPosition = head.Position
    local targetDirection = (targetPosition - headPosition).unit

    -- Calculate the angle between original and target directions
    local angle = math.acos(originalDirection:Dot(targetDirection))
    
    -- Check if the angle exceeds the maximum allowed angle
    if angle > maxAngle then
        -- Clamp the angle
        local axis = originalDirection:Cross(targetDirection).unit
        local clampedDirection = CFrame.fromAxisAngle(axis, maxAngle) * originalDirection
        head.CFrame = CFrame.lookAt(headPosition, headPosition + clampedDirection)
    else
        -- Use the target direction if within the allowed angle
        head.CFrame = CFrame.lookAt(headPosition, targetPosition)
    end
end

-- Example usage
local targetPosition = Vector3.new(10, 5, 0) -- Replace with your target position
clampHeadRotation(targetPosition)

the head is ‘’‘script.parent’‘’

I’ll try this and see id it works