Unlock/Lock Mouse

Hi, I am trying to unlock the mouse when the player clicks the F key, unless it is already locked, it will unlock the mouse, leaving it to move freely. I have this local script in StarterPlayerScripts, and I inserted print statements throughout (which aren’t shown here) to check what was going wrong, and everything works up to the point where it should lock in the uis mouse behaviour part, but nothing happens. Does anyone have an idea what is wrong?

local UIS = game:GetService("UserInputService")
local plr = game.Players.LocalPlayer

UIS.InputBegan:Connect(function(input)
	local rig = workspace:FindFirstChild("Rigs")
	
	if not rig then return end
	
	if input.KeyCode == Enum.KeyCode.F then
		if UIS.MouseBehavior == Enum.MouseBehavior.Default then
			UIS.MouseBehavior = Enum.MouseBehavior.LockCenter
		else
			UIS.MouseBehavior = Enum.MouseBehavior.Default
		end
	end	
end)

Also, the camera is lock first person originally.

Could you add the print statement print(UIS.MouseBehavior) after the player presses F, and tell us what gets thrown in the output?

What if you tried setting a separate variable

local UIS = game:GetService("UserInputService")
local plr = game.Players.LocalPlayer
local isLocked = true

UIS.InputBegan:Connect(function(input)
	local rig = workspace:FindFirstChild("Rigs")
	
	if not rig then return end
	
	if input.KeyCode == Enum.KeyCode.F then
		if isLocked then
            UIS.MouseBehavior = Enum.MouseBehavior.Default
			isLocked = false
		else
            isLocked = true
			UIS.MouseBehavior = Enum.MouseBehavior.LockCenter
		end
	end	
end)

a roblox script probably resets the mousebehavior every frame, so you have to reassign the mouse behavior after that script runs

local runService = game:GetService("RunService")

local function setMouseBehavior() end -- sets the mouse behavior to what its supposed to be

-- try changing the render priority to a bigger value if it doesnt work
runService:BindToRenderStep("setMouseBehavior", Enum.RenderPriority.Character.Value, setMouseBehavior)

I found out it has something to do with it being first person, as when it was third person it worked. I got around it by making the player transparent and put it in an extremely zoomed in thirst person version by changing the min and max zoom distance. Thanks for all the help though!

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.