So I’m modifying an open sourced infinite terrain generator, and have begun making it as lag free as possible, but it’s really tricky to get a decent amount of lag because it creates quite a lot of terrain, and the graphics have to update and apply shadows and all that, creating lag. I have to wait a few frames before loading more terrain, and it’s still laggy and slow.
function module.mountLayer(posX, posZ, height, material)
spawn(function()
if material == Enum.Material.Sand then
workspace.Terrain:FillBlock(CFrame.new(posX + 2, 33.75, posZ + 2), Vector3.new(4, 31.5, 4), Enum.Material.Water) -- Water layer of terrain
end
workspace.Terrain:FillBlock(CFrame.new(posX + 2, height, posZ + 2), Vector3.new(4, 20, 4), material) -- The actual terrain, grass, snow, etc.
wait(.1)
worldGenerator.placeObj(Vector3.new(posX, height, posZ))
end)
end
local loopIndex = 0
function module.makeChunk(posX, posZ) -- Makes a chunk
for x = -chunkSize, chunkSize do
for z = -chunkSize, chunkSize do
local height, material = terrainModule.GetTerrain(posX + (x * 4), posZ + (z * 4)) -- Call's 'TerrainModule' for a height and material
module.mountLayer((x * 4) + posX, (z * 4) + posZ, height + 5, material) -- Actually adds the terrain into the world based on the height and material
if z == chunkSize / 2 then
runService.Stepped:Wait() --We yield for a frame when we do have the z's
end
end
loopIndex += 1
if loopIndex >= loadPerFrame then --loadPerFrame is 1
loopIndex = 0
runService.Stepped:Wait() --We yield for a frame here
end
end
end
With one player, this won’t lag too much (it still lags a little though), and it will most likely lag hard when there’s more than 3 or so, which is pretty bad.
-
What does the code do and what are you not satisfied with? This code generates infinite terrain, and I’m not satisfied because it lags a lot.
-
What potential improvements have you considered? I’m yielding every couple frames, which is a tad slow, and I considered generating less terrain with each chunk (it currently loads terrain as blocks), but this would be difficult to pull off because I need it to be nice and hilly.
-
How (specifically) do you want to improve the code? I want to make it much more performant, especially for more players in the game.
The reason it lags more with more players is because it loads more terrain at the same time for each player. The main cause of this is too much terrain loading at once (I think), but I don’t know how I would get around this.