Custom mouse lock implementation in the easiest way possible!

I have seen many developers being confused about implementing a mouse lock.
As I have found a simple way, Without overriding the PlayerModule as many other tutorials say, So I decided to share it to all.
So here it is:

  1. Locking mouse at the center
local UserInService = game:GetService("UserInputService")
UserInService.MouseBehavior = Enum.MouseBehavior.LockCenter

This will lock the mouse at the center of the screen.

  1. Adding the Mouse Lock Icon
UserInService.MouseIcon = "rbxasset://textures/MouseLockedCursor.png" --Sets Mouse Icon to Locked Cursor Icon

Now after we combine all that and add custom restoration functions, We get:

local userInService = game:GetService("UserInputService")
local mouseLockedIcon = "rbxasset://textures/MouseLockedCursor.png"
local defaultMouseIcon = "rbxasset://SystemCursors/Arrow"
local mouseIconSaved

function LockMouse()
    userInService.MouseBehavior = Enum.MouseBehavior.LockCenter --Lock to center

    mouseIconSaved = UserInService.MouseIcon --Save current mouse icon
    userInService.MouseIcon = mouseLockedIcon --Set Locked mouse Icon
end

function UnlockMouse()
    userInService.MouseBehavior = Enum.MouseBehavior.Default --Unlock Mouse
    
    if mouseIconSaved == nil or mouseIconSaved == "" then mouseIconSaved = defaultMouseIcon end --if Saved Mouse Icon isn't present, then load default in it
    userInService.MouseIcon = mouseIconSaved
end

Now, If I call LockMouse function, it will lock the mouse to the center and display lock Icon. And if I call UnlockMouse function, It will unlock the mouse as expected.

That It for this tutorial, If found helpful leave a like and Thanks!

2 Likes