Help me optimize my speed control local script. (:

Hi,

I made a local script that controls the players speed realistically. I am wondering if there is other ways to optimize my local script. Anything tiny would help me. I am also trying to make it work for future things such as melee hitting or gun shooting.

-- controls movement animation
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")

local LocalPlayer = Players.LocalPlayer
local Camera = workspace.CurrentCamera

local Figure = LocalPlayer.Character
local Humanoid = Figure:WaitForChild("Humanoid")

local MaxSpeed = 13
local WalkLerp: RBXScriptConnection


local function lerp(a, b, t)
	return a + (b - a) * t
end

function OnDirectionChange()
	local RelativeDirection = Humanoid.MoveDirection:Dot(Camera.CFrame.LookVector)

	if RelativeDirection > 0.68 or RelativeDirection > 0.75 then -- foward
		if not WalkLerp then
			WalkLerp = RunService.RenderStepped:Connect(function()		
				
				if RelativeDirection < -0.68 or RelativeDirection < -0.75 or RelativeDirection == 0 then -- just a check
					print("Disconnected from RunService...")
					WalkLerp:Disconnect()
					WalkLerp = nil
				end
				
				Humanoid.WalkSpeed = lerp(Humanoid.WalkSpeed, MaxSpeed, 0.5)
			end)
		end	
	end

	if RelativeDirection < -0.68 or RelativeDirection < -0.75 then
		--print("Backwards")
		Humanoid.WalkSpeed = 6
		if WalkLerp then
			--print("Disconnected")
			WalkLerp:Disconnect()
			WalkLerp = nil
		end
	end

	if RelativeDirection == 0 then -- a or d or standing still
		--print("Sides")
		Humanoid.WalkSpeed = 10
		if WalkLerp then
			--print("Disconnected")
			WalkLerp:Disconnect()
			WalkLerp = nil
		end
	end
end

--RunService.RenderStepped:Connect(OnDirectionChange) -- reliable but very performance heavy
--Humanoid.Running:Connect(OnDirectionChange) -- this isnt very reliable at all
Humanoid:GetPropertyChangedSignal("MoveDirection"):Connect(OnDirectionChange)
1 Like