Advertisement
Guest User

freecam script for roblox

a guest
Jun 7th, 2024
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 14.43 KB | Source Code | 0 0
  1. --!nonstrict
  2. ------------------------------------------------------------------------
  3. -- Freecam
  4. -- Cinematic free camera for spectating and video production.
  5. ------------------------------------------------------------------------
  6.  
  7. local pi    = math.pi
  8. local abs   = math.abs
  9. local clamp = math.clamp
  10. local exp   = math.exp
  11. local rad   = math.rad
  12. local sign  = math.sign
  13. local sqrt  = math.sqrt
  14. local tan   = math.tan
  15.  
  16. local ContextActionService = game:GetService("ContextActionService")
  17. local Players = game:GetService("Players")
  18. local RunService = game:GetService("RunService")
  19. local StarterGui = game:GetService("StarterGui")
  20. local UserInputService = game:GetService("UserInputService")
  21. local Workspace = game:GetService("Workspace")
  22. local Settings = UserSettings()
  23. local GameSettings = Settings.GameSettings
  24.  
  25. local LocalPlayer = Players.LocalPlayer
  26. if not LocalPlayer then
  27.     Players:GetPropertyChangedSignal("LocalPlayer"):Wait()
  28.     LocalPlayer = Players.LocalPlayer
  29. end
  30.  
  31. local Camera = Workspace.CurrentCamera
  32. Workspace:GetPropertyChangedSignal("CurrentCamera"):Connect(function()
  33.     local newCamera = Workspace.CurrentCamera
  34.     if newCamera then
  35.         Camera = newCamera
  36.     end
  37. end)
  38.  
  39. local FFlagUserExitFreecamBreaksWithShiftlock
  40. do
  41.     local success, result = pcall(function()
  42.         return UserSettings():IsUserFeatureEnabled("UserExitFreecamBreaksWithShiftlock")
  43.     end)
  44.     FFlagUserExitFreecamBreaksWithShiftlock = success and result
  45. end
  46.  
  47. local FFlagUserShowGuiHideToggles
  48. do
  49.     local success, result = pcall(function()
  50.         return UserSettings():IsUserFeatureEnabled("UserShowGuiHideToggles")
  51.     end)
  52.     FFlagUserShowGuiHideToggles = success and result
  53. end
  54.  
  55. ------------------------------------------------------------------------
  56.  
  57. local FREECAM_ENABLED_ATTRIBUTE_NAME = "FreecamEnabled"
  58. local TOGGLE_INPUT_PRIORITY = Enum.ContextActionPriority.Low.Value
  59. local INPUT_PRIORITY = Enum.ContextActionPriority.High.Value
  60. local FREECAM_MACRO_KB = {Enum.KeyCode.LeftShift, Enum.KeyCode.P}
  61.  
  62. local NAV_GAIN = Vector3.new(1, 1, 1)*64
  63. local PAN_GAIN = Vector2.new(0.75, 1)*8
  64. local FOV_GAIN = 300
  65.  
  66. local PITCH_LIMIT = rad(90)
  67.  
  68. local VEL_STIFFNESS = 1.5
  69. local PAN_STIFFNESS = 1.0
  70. local FOV_STIFFNESS = 4.0
  71.  
  72. ------------------------------------------------------------------------
  73.  
  74. local Spring = {} do
  75.     Spring.__index = Spring
  76.  
  77.     function Spring.new(freq, pos)
  78.         local self = setmetatable({}, Spring)
  79.         self.f = freq
  80.         self.p = pos
  81.         self.v = pos*0
  82.         return self
  83.     end
  84.  
  85.     function Spring:Update(dt, goal)
  86.         local f = self.f*2*pi
  87.         local p0 = self.p
  88.         local v0 = self.v
  89.  
  90.         local offset = goal - p0
  91.         local decay = exp(-f*dt)
  92.  
  93.         local p1 = goal + (v0*dt - offset*(f*dt + 1))*decay
  94.         local v1 = (f*dt*(offset*f - v0) + v0)*decay
  95.  
  96.         self.p = p1
  97.         self.v = v1
  98.  
  99.         return p1
  100.     end
  101.  
  102.     function Spring:Reset(pos)
  103.         self.p = pos
  104.         self.v = pos*0
  105.     end
  106. end
  107.  
  108. ------------------------------------------------------------------------
  109.  
  110. local cameraPos = Vector3.new()
  111. local cameraRot = Vector2.new()
  112. local cameraFov = 0
  113.  
  114. local velSpring = Spring.new(VEL_STIFFNESS, Vector3.new())
  115. local panSpring = Spring.new(PAN_STIFFNESS, Vector2.new())
  116. local fovSpring = Spring.new(FOV_STIFFNESS, 0)
  117.  
  118. ------------------------------------------------------------------------
  119.  
  120. local Input = {} do
  121.     local thumbstickCurve do
  122.         local K_CURVATURE = 2.0
  123.         local K_DEADZONE = 0.15
  124.  
  125.         local function fCurve(x)
  126.             return (exp(K_CURVATURE*x) - 1)/(exp(K_CURVATURE) - 1)
  127.         end
  128.  
  129.         local function fDeadzone(x)
  130.             return fCurve((x - K_DEADZONE)/(1 - K_DEADZONE))
  131.         end
  132.  
  133.         function thumbstickCurve(x)
  134.             return sign(x)*clamp(fDeadzone(abs(x)), 0, 1)
  135.         end
  136.     end
  137.  
  138.     local gamepad = {
  139.         ButtonX = 0,
  140.         ButtonY = 0,
  141.         DPadDown = 0,
  142.         DPadUp = 0,
  143.         ButtonL2 = 0,
  144.         ButtonR2 = 0,
  145.         Thumbstick1 = Vector2.new(),
  146.         Thumbstick2 = Vector2.new(),
  147.     }
  148.  
  149.     local keyboard = {
  150.         W = 0,
  151.         A = 0,
  152.         S = 0,
  153.         D = 0,
  154.         E = 0,
  155.         Q = 0,
  156.         U = 0,
  157.         H = 0,
  158.         J = 0,
  159.         K = 0,
  160.         I = 0,
  161.         Y = 0,
  162.         Up = 0,
  163.         Down = 0,
  164.         LeftShift = 0,
  165.         RightShift = 0,
  166.     }
  167.  
  168.     local mouse = {
  169.         Delta = Vector2.new(),
  170.         MouseWheel = 0,
  171.     }
  172.  
  173.     local NAV_GAMEPAD_SPEED  = Vector3.new(1, 1, 1)
  174.     local NAV_KEYBOARD_SPEED = Vector3.new(1, 1, 1)
  175.     local PAN_MOUSE_SPEED    = Vector2.new(1, 1)*(pi/64)
  176.     local PAN_GAMEPAD_SPEED  = Vector2.new(1, 1)*(pi/8)
  177.     local FOV_WHEEL_SPEED    = 1.0
  178.     local FOV_GAMEPAD_SPEED  = 0.25
  179.     local NAV_ADJ_SPEED      = 0.75
  180.     local NAV_SHIFT_MUL      = 0.25
  181.  
  182.     local navSpeed = 1
  183.  
  184.     function Input.Vel(dt)
  185.         navSpeed = clamp(navSpeed + dt*(keyboard.Up - keyboard.Down)*NAV_ADJ_SPEED, 0.01, 4)
  186.  
  187.         local kGamepad = Vector3.new(
  188.             thumbstickCurve(gamepad.Thumbstick1.X),
  189.             thumbstickCurve(gamepad.ButtonR2) - thumbstickCurve(gamepad.ButtonL2),
  190.             thumbstickCurve(-gamepad.Thumbstick1.Y)
  191.         )*NAV_GAMEPAD_SPEED
  192.  
  193.         local kKeyboard = Vector3.new(
  194.             keyboard.D - keyboard.A + keyboard.K - keyboard.H,
  195.             keyboard.E - keyboard.Q + keyboard.I - keyboard.Y,
  196.             keyboard.S - keyboard.W + keyboard.J - keyboard.U
  197.         )*NAV_KEYBOARD_SPEED
  198.  
  199.         local shift = UserInputService:IsKeyDown(Enum.KeyCode.LeftShift) or UserInputService:IsKeyDown(Enum.KeyCode.RightShift)
  200.  
  201.         return (kGamepad + kKeyboard)*(navSpeed*(shift and NAV_SHIFT_MUL or 1))
  202.     end
  203.  
  204.     function Input.Pan(dt)
  205.         local kGamepad = Vector2.new(
  206.             thumbstickCurve(gamepad.Thumbstick2.Y),
  207.             thumbstickCurve(-gamepad.Thumbstick2.X)
  208.         )*PAN_GAMEPAD_SPEED
  209.         local kMouse = mouse.Delta*PAN_MOUSE_SPEED
  210.         mouse.Delta = Vector2.new()
  211.         return kGamepad + kMouse
  212.     end
  213.  
  214.     function Input.Fov(dt)
  215.         local kGamepad = (gamepad.ButtonX - gamepad.ButtonY)*FOV_GAMEPAD_SPEED
  216.         local kMouse = mouse.MouseWheel*FOV_WHEEL_SPEED
  217.         mouse.MouseWheel = 0
  218.         return kGamepad + kMouse
  219.     end
  220.  
  221.     do
  222.         local function Keypress(action, state, input)
  223.             keyboard[input.KeyCode.Name] = state == Enum.UserInputState.Begin and 1 or 0
  224.             return Enum.ContextActionResult.Sink
  225.         end
  226.  
  227.         local function GpButton(action, state, input)
  228.             gamepad[input.KeyCode.Name] = state == Enum.UserInputState.Begin and 1 or 0
  229.             return Enum.ContextActionResult.Sink
  230.         end
  231.  
  232.         local function MousePan(action, state, input)
  233.             local delta = input.Delta
  234.             mouse.Delta = Vector2.new(-delta.y, -delta.x)
  235.             return Enum.ContextActionResult.Sink
  236.         end
  237.  
  238.         local function Thumb(action, state, input)
  239.             gamepad[input.KeyCode.Name] = input.Position
  240.             return Enum.ContextActionResult.Sink
  241.         end
  242.  
  243.         local function Trigger(action, state, input)
  244.             gamepad[input.KeyCode.Name] = input.Position.z
  245.             return Enum.ContextActionResult.Sink
  246.         end
  247.  
  248.         local function MouseWheel(action, state, input)
  249.             mouse[input.UserInputType.Name] = -input.Position.z
  250.             return Enum.ContextActionResult.Sink
  251.         end
  252.  
  253.         local function Zero(t)
  254.             for k, v in pairs(t) do
  255.                 t[k] = v*0
  256.             end
  257.         end
  258.  
  259.         function Input.StartCapture()
  260.             ContextActionService:BindActionAtPriority("FreecamKeyboard", Keypress, false, INPUT_PRIORITY,
  261.                 Enum.KeyCode.W, Enum.KeyCode.U,
  262.                 Enum.KeyCode.A, Enum.KeyCode.H,
  263.                 Enum.KeyCode.S, Enum.KeyCode.J,
  264.                 Enum.KeyCode.D, Enum.KeyCode.K,
  265.                 Enum.KeyCode.E, Enum.KeyCode.I,
  266.                 Enum.KeyCode.Q, Enum.KeyCode.Y,
  267.                 Enum.KeyCode.Up, Enum.KeyCode.Down
  268.             )
  269.             ContextActionService:BindActionAtPriority("FreecamMousePan",          MousePan,   false, INPUT_PRIORITY, Enum.UserInputType.MouseMovement)
  270.             ContextActionService:BindActionAtPriority("FreecamMouseWheel",        MouseWheel, false, INPUT_PRIORITY, Enum.UserInputType.MouseWheel)
  271.             ContextActionService:BindActionAtPriority("FreecamGamepadButton",     GpButton,   false, INPUT_PRIORITY, Enum.KeyCode.ButtonX, Enum.KeyCode.ButtonY)
  272.             ContextActionService:BindActionAtPriority("FreecamGamepadTrigger",    Trigger,    false, INPUT_PRIORITY, Enum.KeyCode.ButtonR2, Enum.KeyCode.ButtonL2)
  273.             ContextActionService:BindActionAtPriority("FreecamGamepadThumbstick", Thumb,      false, INPUT_PRIORITY, Enum.KeyCode.Thumbstick1, Enum.KeyCode.Thumbstick2)
  274.         end
  275.  
  276.         function Input.StopCapture()
  277.             navSpeed = 1
  278.             Zero(gamepad)
  279.             Zero(keyboard)
  280.             Zero(mouse)
  281.             ContextActionService:UnbindAction("FreecamKeyboard")
  282.             ContextActionService:UnbindAction("FreecamMousePan")
  283.             ContextActionService:UnbindAction("FreecamMouseWheel")
  284.             ContextActionService:UnbindAction("FreecamGamepadButton")
  285.             ContextActionService:UnbindAction("FreecamGamepadTrigger")
  286.             ContextActionService:UnbindAction("FreecamGamepadThumbstick")
  287.         end
  288.     end
  289. end
  290.  
  291. ------------------------------------------------------------------------
  292.  
  293. local function StepFreecam(dt)
  294.     local vel = velSpring:Update(dt, Input.Vel(dt))
  295.     local pan = panSpring:Update(dt, Input.Pan(dt))
  296.     local fov = fovSpring:Update(dt, Input.Fov(dt))
  297.  
  298.     local zoomFactor = sqrt(tan(rad(70/2))/tan(rad(cameraFov/2)))
  299.  
  300.     cameraFov = clamp(cameraFov + fov*FOV_GAIN*(dt/zoomFactor), 1, 120)
  301.     cameraRot = cameraRot + pan*PAN_GAIN*(dt/zoomFactor)
  302.     cameraRot = Vector2.new(clamp(cameraRot.x, -PITCH_LIMIT, PITCH_LIMIT), cameraRot.y%(2*pi))
  303.  
  304.     local cameraCFrame = CFrame.new(cameraPos)*CFrame.fromOrientation(cameraRot.x, cameraRot.y, 0)*CFrame.new(vel*NAV_GAIN*dt)
  305.     cameraPos = cameraCFrame.p
  306.  
  307.     Camera.CFrame = cameraCFrame
  308.     Camera.Focus = cameraCFrame
  309.     Camera.FieldOfView = cameraFov
  310. end
  311.  
  312. local function CheckMouseLockAvailability()
  313.     local devAllowsMouseLock = Players.LocalPlayer.DevEnableMouseLock
  314.     local devMovementModeIsScriptable = Players.LocalPlayer.DevComputerMovementMode == Enum.DevComputerMovementMode.Scriptable
  315.     local userHasMouseLockModeEnabled = GameSettings.ControlMode == Enum.ControlMode.MouseLockSwitch
  316.     local userHasClickToMoveEnabled =  GameSettings.ComputerMovementMode == Enum.ComputerMovementMode.ClickToMove
  317.     local MouseLockAvailable = devAllowsMouseLock and userHasMouseLockModeEnabled and not userHasClickToMoveEnabled and not devMovementModeIsScriptable
  318.  
  319.     return MouseLockAvailable
  320. end
  321.  
  322. ------------------------------------------------------------------------
  323.  
  324. local PlayerState = {} do
  325.     local mouseBehavior
  326.     local mouseIconEnabled
  327.     local cameraType
  328.     local cameraFocus
  329.     local cameraCFrame
  330.     local cameraFieldOfView
  331.     local screenGuis = {}
  332.     local coreGuis = {
  333.         Backpack = true,
  334.         Chat = true,
  335.         Health = true,
  336.         PlayerList = true,
  337.     }
  338.     local setCores = {
  339.         BadgesNotificationsActive = true,
  340.         PointsNotificationsActive = true,
  341.     }
  342.  
  343.     -- Save state and set up for freecam
  344.     function PlayerState.Push()
  345.         for name in pairs(coreGuis) do
  346.             coreGuis[name] = StarterGui:GetCoreGuiEnabled(Enum.CoreGuiType[name])
  347.             StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType[name], false)
  348.         end
  349.         for name in pairs(setCores) do
  350.             setCores[name] = StarterGui:GetCore(name)
  351.             StarterGui:SetCore(name, false)
  352.         end
  353.         local playergui = LocalPlayer:FindFirstChildOfClass("PlayerGui")
  354.         if playergui then
  355.             for _, gui in pairs(playergui:GetChildren()) do
  356.                 if gui:IsA("ScreenGui") and gui.Enabled then
  357.                     screenGuis[#screenGuis + 1] = gui
  358.                     gui.Enabled = false
  359.                 end
  360.             end
  361.         end
  362.  
  363.         cameraFieldOfView = Camera.FieldOfView
  364.         Camera.FieldOfView = 70
  365.  
  366.         cameraType = Camera.CameraType
  367.         Camera.CameraType = Enum.CameraType.Custom
  368.  
  369.         cameraCFrame = Camera.CFrame
  370.         cameraFocus = Camera.Focus
  371.  
  372.         mouseIconEnabled = UserInputService.MouseIconEnabled
  373.         UserInputService.MouseIconEnabled = false
  374.  
  375.         if FFlagUserExitFreecamBreaksWithShiftlock and CheckMouseLockAvailability() then
  376.             mouseBehavior = Enum.MouseBehavior.Default
  377.         else
  378.             mouseBehavior = UserInputService.MouseBehavior
  379.         end
  380.         UserInputService.MouseBehavior = Enum.MouseBehavior.Default
  381.     end
  382.  
  383.     -- Restore state
  384.     function PlayerState.Pop()
  385.         for name, isEnabled in pairs(coreGuis) do
  386.             StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType[name], isEnabled)
  387.         end
  388.         for name, isEnabled in pairs(setCores) do
  389.             StarterGui:SetCore(name, isEnabled)
  390.         end
  391.         for _, gui in pairs(screenGuis) do
  392.             if gui.Parent then
  393.                 gui.Enabled = true
  394.             end
  395.         end
  396.  
  397.         Camera.FieldOfView = cameraFieldOfView
  398.         cameraFieldOfView = nil
  399.  
  400.         Camera.CameraType = cameraType
  401.         cameraType = nil
  402.  
  403.         Camera.CFrame = cameraCFrame
  404.         cameraCFrame = nil
  405.  
  406.         Camera.Focus = cameraFocus
  407.         cameraFocus = nil
  408.  
  409.         UserInputService.MouseIconEnabled = mouseIconEnabled
  410.         mouseIconEnabled = nil
  411.  
  412.         UserInputService.MouseBehavior = mouseBehavior
  413.         mouseBehavior = nil
  414.     end
  415. end
  416.  
  417. local function StartFreecam()
  418.     if FFlagUserShowGuiHideToggles then
  419.         script:SetAttribute(FREECAM_ENABLED_ATTRIBUTE_NAME, true)
  420.     end
  421.  
  422.     local cameraCFrame = Camera.CFrame
  423.     cameraRot = Vector2.new(cameraCFrame:toEulerAnglesYXZ())
  424.     cameraPos = cameraCFrame.p
  425.     cameraFov = Camera.FieldOfView
  426.  
  427.     velSpring:Reset(Vector3.new())
  428.     panSpring:Reset(Vector2.new())
  429.     fovSpring:Reset(0)
  430.  
  431.     PlayerState.Push()
  432.     RunService:BindToRenderStep("Freecam", Enum.RenderPriority.Camera.Value, StepFreecam)
  433.     Input.StartCapture()
  434. end
  435.  
  436. local function StopFreecam()
  437.     if FFlagUserShowGuiHideToggles then
  438.         script:SetAttribute(FREECAM_ENABLED_ATTRIBUTE_NAME, false)
  439.     end
  440.  
  441.     Input.StopCapture()
  442.     RunService:UnbindFromRenderStep("Freecam")
  443.     PlayerState.Pop()
  444. end
  445.  
  446. ------------------------------------------------------------------------
  447.  
  448. do
  449.     local enabled = false
  450.  
  451.     local function ToggleFreecam()
  452.         if enabled then
  453.             StopFreecam()
  454.         else
  455.             StartFreecam()
  456.         end
  457.         enabled = not enabled
  458.     end
  459.  
  460.     local function CheckMacro(macro)
  461.         for i = 1, #macro - 1 do
  462.             if not UserInputService:IsKeyDown(macro[i]) then
  463.                 return
  464.             end
  465.         end
  466.         ToggleFreecam()
  467.     end
  468.  
  469.     local function HandleActivationInput(action, state, input)
  470.         if state == Enum.UserInputState.Begin then
  471.             if input.KeyCode == FREECAM_MACRO_KB[#FREECAM_MACRO_KB] then
  472.                 CheckMacro(FREECAM_MACRO_KB)
  473.             end
  474.         end
  475.         return Enum.ContextActionResult.Pass
  476.     end
  477.  
  478.     ContextActionService:BindActionAtPriority("FreecamToggle", HandleActivationInput, false, TOGGLE_INPUT_PRIORITY, FREECAM_MACRO_KB[#FREECAM_MACRO_KB])
  479.  
  480.     if FFlagUserShowGuiHideToggles then
  481.         script:SetAttribute(FREECAM_ENABLED_ATTRIBUTE_NAME, enabled)
  482.         script:GetAttributeChangedSignal(FREECAM_ENABLED_ATTRIBUTE_NAME):Connect(function()
  483.             local attributeValue = script:GetAttribute(FREECAM_ENABLED_ATTRIBUTE_NAME)
  484.  
  485.             if typeof(attributeValue) ~= "boolean" then
  486.                 script:SetAttribute(FREECAM_ENABLED_ATTRIBUTE_NAME, enabled)
  487.                 return
  488.             end
  489.  
  490.             -- If the attribute's value and `enabled` var don't match, pick attribute value as
  491.             -- source of truth
  492.             if attributeValue ~= enabled then
  493.                 if attributeValue then
  494.                     StartFreecam()
  495.                     enabled = true
  496.                 else
  497.                     StopFreecam()
  498.                     enabled = false
  499.                 end
  500.             end
  501.         end)
  502.     end
  503. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement