How to Force Mouse Lock Easily!

Hey everyone! I was looking around to find a good way for a developer to toggle a player’s mouse lock through scripts, and I couldn’t find a way to do so that was simple enough without some wacky hacks.

And, well, yeah. You kinda have to do some wacky hacks. But to save everyone time and energy, I made it easy. Here is a modified PlayerModule that lets you easily toggle it in any LocalScript any time you want.

Put the modified PlayerModule in StarterPlayerScripts, and then all you have to do is type in the script you’re working with:

Player:SetAttribute("MouseLockEnabled", true) 

Or, you can set the value to false to turn off the mouse lock.

Player:SetAttribute("MouseLockEnabled", false) 

Or, you make your own script!

In case you’re paranoid about this being a back door, or you already have a modified PlayerModule of your own that you would like to edit to include this functionality, all you have to do is find the CameraModule script in the PlayerModule that Roblox uses and paste this code at the end of the :Update(dt) function. You should be able to find this on line 492.

if game.Players.LocalPlayer:GetAttribute("MouseLockEnabled") == true then
	self.activeCameraController:SetIsMouseLocked(true)
else
	self.activeCameraController:SetIsMouseLocked(false)
end

local mouseLockOffset = self.activeMouseLockController:GetMouseLockOffset()
self.activeCameraController:SetMouseLockOffset(mouseLockOffset)
22 Likes

I had to modify this because if the attribute “MouseLockEnabled” is set to false, it won’t run the entire code block which makes you stuck in mouse lock.

Should be replaced with something like

        if game.Players.LocalPlayer:GetAttribute("MouseLockEnabled") == true then
			self.activeCameraController:SetIsMouseLocked(true)
		else
			self.activeCameraController:SetIsMouseLocked(false)
		end
		local mouseLockOffset = self.activeMouseLockController:GetMouseLockOffset()
		self.activeCameraController:SetMouseLockOffset(mouseLockOffset)

Thanks for pointing this out! I’ve updated my model to Roblox. I never realized since I only have to enable it once for my current use case.

2 Likes

When i do this: Player:SetAttribute(“MouseLockEnabled”, false) it still stays locked

1 Like