How to optimize this script as much as possible

So, i have a script that moves camera to the mouse, like this:

heres the code:


--// Variables
local tweenService = game:GetService("TweenService")

local cam = workspace.CurrentCamera
local mouse = game:GetService("Players").LocalPlayer:GetMouse()
local DefaultCFrame = CFrame.new(-550.785034, 4.64243889, -321.344604, 0.780983269, -0.0947338939, 0.617325425, -0, 0.988429308, 0.151682958, -0.624552011, -0.118461855, 0.771946669)

local tweenInfo = TweenInfo.new(0.4,Enum.EasingStyle.Quad,Enum.EasingDirection.Out)
--// Set cam
repeat
	task.wait()
	cam.CameraType = Enum.CameraType.Scriptable
until cam.CameraType == Enum.CameraType.Scriptable


cam.CFrame = DefaultCFrame
--// Move cam
local maxTilt = 10

game:GetService("RunService").Heartbeat:Connect(function()
	local goal = {CFrame = DefaultCFrame * CFrame.Angles(
		math.rad((((mouse.Y - mouse.ViewSizeY / 2) / mouse.ViewSizeY)) * -maxTilt),
		math.rad((((mouse.X - mouse.ViewSizeX / 2) / mouse.ViewSizeX)) * -maxTilt),
		0
		)}
	tweenService:Create(cam,tweenInfo,goal):Play()
end)

Preferably, do not use tweenService in every step of the game.

local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local cam = workspace.CurrentCamera
local DefaultCFrame = CFrame.new(-550.785034, 4.64243889, -321.344604, 0.780983269, -0.0947338939, 0.617325425, -0, 0.988429308, 0.151682958, -0.624552011, -0.118461855, 0.771946669)

local maxTilt = 8 
local smoothingFactor = 6 

task.wait()
cam.CameraType = Enum.CameraType.Scriptable
cam.CameraSubject = nil
cam.CFrame = DefaultCFrame

RunService.RenderStepped:Connect(function(dt)
	cam.CameraType = Enum.CameraType.Scriptable 

	local viewportSize = cam.ViewportSize
	local centerX = viewportSize.X / 2
	local centerY = viewportSize.Y / 2

	local mouseOffsetX = (mouse.X - centerX) / centerX
	local mouseOffsetY = (mouse.Y - centerY) / centerY

	local goalCFrame = DefaultCFrame * CFrame.Angles(
		math.rad(mouseOffsetY * -maxTilt),
		math.rad(mouseOffsetX * -maxTilt),
		0
	)

	local alpha = 1 - math.exp(-dt * smoothingFactor)
	cam.CFrame = cam.CFrame:Lerp(goalCFrame, alpha)
end)

3 Likes

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