Need help with optimization of my leaves movement script

Hello scripters and developers, I made a script that simulates leaves movement, but the script usage(%) and the rate/s are kinda high, i need a way to fix that

and overall the script is not well optimized and makes the game not run as smoothly as i want :frowning:

if any of you can give me a fixed code of it it would help me very much

here is the script:

local RunService = game:GetService("RunService")

local function updatePosition(leafPart)
	local pos = leafPart.Position
	local tall = leafPart.Size.Y / 2
	local T = -99999
	local counter = 0
	local updateFrequency = 10 -- Update every 10 heartbeats

	return function()
		counter = counter + 1
		if counter >= updateFrequency then
			counter = 0

			local x = pos.X + (math.sin(T + (pos.X / 5)) * math.sin(T / 9)) / 3
			local z = pos.Z + (math.sin(T + (pos.Z / 6)) * math.sin(T / 12)) / 4

			leafPart.CFrame = CFrame.new(x, pos.Y, z) * CFrame.Angles((z - pos.Z) / tall, 0, (x - pos.X) / -tall)

			T = T + 0.12
		end
	end
end

local function connectLeaves()
	local leaves = workspace:GetDescendants()

	for _, leafPart in ipairs(leaves) do
		if leafPart:IsA("BasePart") and leafPart.Name == "Leaves" then
			local updateFunc = updatePosition(leafPart)
			RunService.Heartbeat:Connect(updateFunc)
		end
	end
end

connectLeaves() -- Initially connect leaves

As you can see in the image down below, you can see that my script (the one in the middle) has an high activity and utilization rate:

image

you should consider two things. updateFrequency is quite high, it practically makes the animation run 6 fps, you probably want to reduce it to 2 or 3 (even 4 might be acceptable). When doing RunService.Heartbeat:Connect(updateFunc), all animations start and update at the same time which can cause lag if you have a lot of parts, to improve that you can add a task.wait() after RunService.Heartbeat:Connect(updateFunc). This way the animations will start a frame after the previous one and it will look more organic.

if you still have problems, more details would be helpful.

Happy Holidays.

1 Like

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