How to properly use Perlin noise to create blocky caves?

Hello developers,

I am working on an infinite mining game and I wanted it to have random cave generation. Problem is, I’ve never used noise before.

I found a tutorial online on how to do it, and whenever I run the code I get a result that looks like this:

That’s kind of what I want, but there’s a few problems. As you can see at the top, the cave ends up breaking the surface and cutting off the edges, which I could just fill up with blocks, but that would look unnatural.

The second problem is that there’s a ton of useless blocks that were generated, which won’t be seen by the player if they’re inside the cave. Instead, I’d prefer if it generated something like this:

Unfortunately as mentioned, I am new to Perlin noise, and I’ve not sure how to achieve that.

Any help would be appreciated.

Here’s the code that I used.

local seed = math.random(1,10000000)
local caveSizeX = math.random(5,50)
local caveSizeY = math.random(5,50)
local caveSizeZ = math.random(5,50)

noiseScale = 20
amplitude = 40
blocksize = 6

for x = 0,caveSizeX do
	for z = 0,caveSizeZ do
		for y = 0,caveSizeY do
			xNoise = math.noise(y/noiseScale,z/noiseScale,seed) * amplitude
			yNoise = math.noise(x/noiseScale,z/noiseScale,seed) * amplitude
			zNoise = math.noise(x/noiseScale,y/noiseScale,seed) * amplitude	
			
			density = xNoise + yNoise + zNoise
			if density < 10 then
				part = Instance.new("Part",workspace)
				part.Anchored = true
				part.Size = Vector3.new(blocksize,blocksize,blocksize)
				part.CFrame = CFrame.new(x*blocksize,y*blocksize, z*blocksize)
			end
		end
	end
	wait()
end

Thanks in advance!

P.S: I know there’s already a topic on this, but it doesn’t really cover what I want to achieve.

P.S.S: I’m aware of this game that has random caves is uncopylocked, but when I open it, Studio takes several minutes to load it and then gives me an error.

1 Like