Making a no-repeat generator

Hi there, I’m working on a infinite terrain generator using math.noise. Everythings mostly gone fine, but I’ve ran in to a problem: “chunks” of land regenerating themselves. What I mean is, my script checks the chunk that the player is in and generates it. However, it’s not very optimised because it’ll keep regenerating the chunk that the player is in, where else it could be doing something else. Here’s my code, so you can have a check:

local frame = player.Character:GetPrimaryPartCFrame()
chunkX = math.floor(frame.Position.X / 40)
chunkY = math.floor(frame.Position.Z / 40)
generateChunk(1.234, Vector2.new(tempvar1 * 40, tempvar2 * 40))

A little info: each chunk is 80 x 80 studs big, and the first number in the generateChunk is the seed.

So, as you can see, there’s no protection against regenerating chunks. I tried making a “has chunk generated system”, like this:

local chunkGened = {}

and in the first script:

if chunkGened[chunkX][chunkY] == nil then
--do the generation part
chunkGened[chunkX][chunkY] = true --just a value

But, it STILL didn’t work. I have no idea what’s wrong with it.
I thought that maybe since the first part of the array didn’t exist yet, it couldn’t do it so I tried this:

if chunkGened[chunkX] == nil then
chunkGened[chunkX] = {true}
end

but it still didn’t work. I have no idea, any help would be very nice.
thanks!

2 Likes

Here’s a snippet I’ve used across tonnes of projects:

function mapGet(map, x, y)
    if map[x] then
        return map[x][y]
    end
end

function mapSet(map, x, y, value)
    map[x] = map[x] or {}
    map[x][y] = value
end

local generatedMap = {}

... before generating a chunk

if not mapGet(generatedMap, chunkX, chunkY) then
    --Generate this chunk
end

...  when generating a chunk

mapSet(generatedMap, chunkX, chunkY, true)

... when unloading a chunk

mapSet(generatedMap, chunkX, chunkY, false)

Ask away if something is unclear :slight_smile:

1 Like