I wrote a gui sway script, however everytime I move slowly, it is very choppy in terms of FPS. My code can be seen below. How could I fix it?
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local TweenService = game:GetService("TweenService")
local exclusions = {
-- List GUI objects to exclude from the sway effect
--game:GetService("StarterGui").Loading,
game:GetService("StarterGui").LensFlareGui
}
local function applySwayEffect(gui)
local guiPosition = gui.Position
local guiOffset = guiPosition
local X = {["Goal"] = 0, ["Tween"] = nil, ["Value"] = Instance.new("NumberValue")}
local Y = {["Goal"] = 0, ["Tween"] = nil, ["Value"] = Instance.new("NumberValue")}
RunService.RenderStepped:Connect(function(DeltaTime)
local MouseDelta = UserInputService:GetMouseDelta() * 0.5
if X.Goal ~= MouseDelta.X then
if X.Tween then
X.Tween:Cancel()
X.Tween = nil
end
X.Goal = MouseDelta.X
X.Tween = TweenService:Create(X.Value, TweenInfo.new(0.5, Enum.EasingStyle.Sine, Enum.EasingDirection.Out), {["Value"] = MouseDelta.X})
X.Tween:Play()
end
if Y.Goal ~= MouseDelta.Y then
if Y.Tween then
Y.Tween:Cancel()
Y.Tween = nil
end
Y.Goal = MouseDelta.Y
Y.Tween = TweenService:Create(Y.Value, TweenInfo.new(0.5, Enum.EasingStyle.Sine, Enum.EasingDirection.Out), {["Value"] = MouseDelta.Y})
Y.Tween:Play()
end
guiOffset = UDim2.fromOffset(X.Value.Value, Y.Value.Value)
TweenService:Create(gui, TweenInfo.new(0.1, Enum.EasingStyle.Sine, Enum.EasingDirection.Out, 0, false, 0), {Position = guiPosition + guiOffset}):Play()
--gui.Position = guiPosition + guiOffset
end)
end
local function applySwayEffectToAllGUIs(gui)
for _, child in ipairs(gui:GetDescendants()) do
if child:IsA("GuiObject") then
local exclude = false
for _, exclusion in ipairs(exclusions) do
if child == exclusion or child:IsDescendantOf(exclusion) then
exclude = true
break
end
end
if not exclude then
applySwayEffect(child)
end
end
end
end
applySwayEffectToAllGUIs(game:GetService("StarterGui"))
game.Players.LocalPlayer.PlayerGui.DescendantAdded:Connect(function(child)
if child:IsA("GuiObject") then
local exclude = false
for _, exclusion in ipairs(exclusions) do
if child == exclusion or child:IsDescendantOf(exclusion) then
exclude = true
break
end
end
if not exclude then
applySwayEffect(child)
end
end
end)