Testing with gerstner waves makes a lot of lag (solved)

Hello people! I am testing out cool wave functions and have come across gerstner waves. I made a script to spawn parts and move them in the wave, and it works well except for the fact that it is incredibly laggy. Even with only 30 parts moving, it makes a ton of lag. Any ideas on how I can reduce the lag so I might be able to use it for a real project? One idea i have is to make it update less frequently and instead tween or lerp the parts, but i feel like that will make the quality of the waves worse. Here’s my code:

for i = 1,30 do
	local newpart = Instance.new("Part",script.Parent)
	newpart.Size = Vector3.new(.5,.5,.5)
	newpart.Anchored = true
	newpart.Material = Enum.Material.SmoothPlastic
	newpart.BrickColor = BrickColor.Green()
end

local k = 0.5
local c = 0.5
local a = 1.5

local function calculate(X,T)
	print(X, T)
	local x = k * (X-(c*T))
	return x
end

local ticks = 0
while true do
	ticks += 1
    wait()
	for i,v in pairs(script.Parent:GetChildren()) do
		if v:IsA("Part") then
			local pos = Vector3.new(i + (0.1 * math.cos(ticks)) + (a * math.cos(calculate(i,ticks))),(0.1 * math.sin(ticks)) + (a * math.sin(calculate(i,ticks))),0)
			v.Position = pos + Vector3.new(-20,5,20) -- this just sets the part position and moves it higher.
		end
	end
end

Yeah, remove your print function. It’s causing the lag.

Edit Though, additionally, by using task.wait() instead of wait and utilizing a local table instead of calling :GetChildren() every interval - you can get pretty much 60Hz no lag.

local parts = {}

for i = 1,30 do
	local newpart = Instance.new("Part")
	newpart.Size = Vector3.new(.5,.5,.5)
	newpart.Anchored = true
	newpart.Material = Enum.Material.SmoothPlastic
	newpart.BrickColor = BrickColor.Green()
	newpart.Parent = workspace
	table.insert(parts, newpart)
end

local k = 0.5
local c = 0.5
local a = 1.5

local function calculate(X,T)
	local x = k * (X-(c*T))
	return x
end

local ticks = 0
while true do
	ticks += 1
	task.wait()
	for i,v in pairs(parts) do
		local pos = Vector3.new(i + (0.1 * math.cos(ticks)) + (a * math.cos(calculate(i,ticks))),(0.1 * math.sin(ticks)) + (a * math.sin(calculate(i,ticks))),0)
		v.Position = pos + Vector3.new(-20,5,20) -- this just sets the part position and moves it higher.
	end
end
3 Likes

Haha I wish it was the culprit

I was being 100% serious. I removed your print call and it removed the majority of the lag. With my version above, this is the frames I am getting.

Versus yours

1 Like

Oh wow I really didn’t expect the print to create any lag at all, thank you!