Issue with chunk-based terrain generation

I want the terrain out of a certain boundary to unload, and terrain in a certain boundary to load.

The code I have made does not unload the terrain properly, where the farther the player gets from the world origin, the closer the unloaded terrain boundary gets, until the player falls into the void. But the main issue is that I do not know what problematic code is.

I have commented almost everything just in case I could catch anything, but this did not work.

Here is the rbxl file so you can test it yourself:
Newest Version:
TerrainGen.rbxl (66.3 KB)

TerrainGen.rbxl (55.4 KB)

The script that generates terrain is a local script inside StarterPlayerScripts.

Update:
Tested values for “chunk_x” in the for loop around line 199 (may differ since I have been making changes) and got this:
image
Since render distance is currently set to 10, this should not be printing. It should go from -500 to 500 in 100 stud increments (which would print 10 things before repeating), but it does not.
Below is an image of what the terrain looks like during this bug.


More info later

use math.clamp

h = math.clamp(h, -0.5, 0.5) + 0.5

What does that have to do with the x and z positions?

it locks the positions is that not what you wanted? i might’ve read it wrong :smiley:

Ah ok, I don’t need any further help though, thanks for trying!