How would I toggle the players toggle forcing a player into shiftlock?

I’ve made a flying script in studio, it works well but only in shiftlock. Is there anyway to force the player into shiftlock when flying, then letting them come out of it when not flying?

I’ve already tried looking for solutions, but everything was just forcing players into shiftlock right from when they join to when they leave.

I have my own variable: local flying = false, so I can easily toggle when its on/off.

You’ll be using MouseBehavior to achieve this behavior!

game:GetService("UserInputService").MouseBehavior = Enum.MouseBehavior.LockCenter  -- Force shift lock

This does work in locking the mouse, but it isn’t really shiftlock as the camera is still free to move around the player.

Sorry for the late reply.

Just change aim to flying

local Camera = game.Workspace.CurrentCamera
local player = game.Players.LocalPlayer
local Character = player.Character 
local rootPart = Character:FindFirstChild("HumanoidRootPart")
local mouse = player:GetMouse()
local aim = false
local runService = game:GetService("RunService")

runService.RenderStepped:Connect(function()
	if aim == true then
		local rx, ry, rz = Camera.CFrame:ToOrientation()
		rootPart.CFrame = CFrame.new(rootPart.CFrame.p) * CFrame.fromOrientation(0, ry, 0)
	end
		
end)
mouse.Button1Down:Connect(function()
	aim = true
end)
mouse.Button1Up:Connect(function()
	aim = false
end)