Home > Blockchain >  Unity - Infinite terrain gaps betwean chunks?
Unity - Infinite terrain gaps betwean chunks?

Time:12-25

So I am creating an endless terrain.

I can create the terrain but my chunks have gaps betwean them and they don't align properly.

I think the problem might be caused by my Noise Generation script, but I am not sure.

This is my Noise Generation script

public static class Noise_GENERATOR
    {
        public static float[,] GenerateNoise(int chunkSize, int octaves, int seed, float noiseScale, float persistence, float lacunarity, Vector2 offset)
        {
    
            float[,] noiseMap = new float[chunkSize, chunkSize];
    
            System.Random prng = new System.Random(seed);
            Vector2[] octaveOffsets = new Vector2[octaves];
    
            float maxPossibleHeight = 0;
            float amplitude = 1;
            float frequency = 1;
    
            for (int i = 0; i < octaves; i  )
            {
                float offsetX = prng.Next(-100000, 100000)   offset.x;
                float offsetY = prng.Next(-100000, 100000)   offset.y;
                octaveOffsets[i] = new Vector2(offsetX, offsetY);
    
                maxPossibleHeight  = amplitude;
                amplitude *= persistence;
            }
    
            if (noiseScale <= 0)
            {
                noiseScale = 0.0001f;
            }
    
            float maxLocalNoiseHeight = float.MinValue;
            float minLocalNoiseHeight = float.MaxValue;
    
            float halfWidth = chunkSize / 2f;
            float halfHeight = chunkSize / 2f;
    
    
            for (int y = 0; y < chunkSize; y  )
            {
                for (int x = 0; x < chunkSize; x  )
                {
    
                    amplitude = 1;
                    frequency = 1;
                    float noiseHeight = 0;
    
                    for (int i = 0; i < octaves; i  )
                    {
                        float sampleX = (x-halfWidth   octaveOffsets[i].x) / noiseScale * frequency;
                        float sampleY = (y-halfHeight   octaveOffsets[i].y) / noiseScale * frequency;
    
                        float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1;
                        noiseHeight  = perlinValue * amplitude;
    
                        amplitude *= persistence;
                        frequency *= lacunarity;
                    }
    
                    if (noiseHeight > maxLocalNoiseHeight)
                    {
                        maxLocalNoiseHeight = noiseHeight;
                    }
                    else if (noiseHeight < minLocalNoiseHeight)
                    {
                        minLocalNoiseHeight = noiseHeight;
                    }
                    noiseMap[x, y] = noiseHeight;
    
                    float normalizedHeight = (noiseMap[x, y]   1) / (maxPossibleHeight / 0.9f);
                    noiseMap[x, y] = Mathf.Clamp(normalizedHeight, 0, int.MaxValue);
                }
            }
    
            return noiseMap;
        }
    }

To Generate the height of a mesh, I am using Animation Curve and multiplying it by elevationScale variable.

                 float height = heightCurve.Evaluate(noiseMap[x, y]) * elevationScale;

These gaps are created betwean chunks This is how the gaps looks like in the Y noise offset enter image description here

I thought about accesing each Terrain chunk and getting the height of the edges and matching them together but that would look really weird and I don't know how to do it properly.

EDIT: Here just in case my Mesh generator script and how I am creating the Terrain chunk

    public  static class Mesh_GENERATOR 
{
    public static MeshData GenerateChunkMesh(int chunkSize,float[,] noiseMapData,float elevationScale,AnimationCurve terrainCurve,int LODlevel )
    {
        float[,] noiseMap = noiseMapData;
        AnimationCurve heightCurve = new AnimationCurve(terrainCurve.keys);
        //Setup variables
        Vector3[] vertices = new Vector3[chunkSize * chunkSize];
        int[] triangles = new int[(chunkSize - 1) * (chunkSize - 1) * 6];
        Vector2[] uvs = new Vector2[chunkSize * chunkSize];
        int triangle = 0;

        int levelOfDetailIncrement = (LODlevel == 0) ? 1 : LODlevel * 2;
        int numberOfVerticesPerRow = (chunkSize) / levelOfDetailIncrement   1;
 
        for (int y = 0; y < chunkSize; y  )
        {
            for (int x = 0; x < chunkSize; x  )
            {
                int i = y * chunkSize   x;

                //Create vertices at position and center mesh

                float height = heightCurve.Evaluate(noiseMap[x, y]) * elevationScale;
                Vector2 percentPosition = new Vector2(x / (chunkSize - 1f), y / (chunkSize -1f ));

                Vector3 vertPosition = new Vector3(percentPosition.x * 2 - 1, 0, percentPosition.y * 2 - 1) * chunkSize/2;

                vertPosition.y = height;
                vertices[i] = vertPosition;
               
                uvs[i] = new Vector2((float)x / chunkSize, (float)y / chunkSize);

                //Construct triangles
                if (x != chunkSize - 1 && y != chunkSize - 1)
                {
                    triangles[triangle   0] = i   chunkSize;
                    triangles[triangle   1] = i   chunkSize   1;
                    triangles[triangle   2] = i;

                    triangles[triangle   3] = i   chunkSize   1;
                    triangles[triangle   4] = i   1;
                    triangles[triangle   5] = i;
                    triangle  = 6;
                }
            }
        }

        MeshData meshData = new MeshData(chunkSize, vertices, triangles, uvs);
        return meshData;
    }
}

public class MeshData
{
    public int chunkSize;
    public Vector3[] vertices;
    public int[] triangles;
    public Vector2[] uvs;

    public Mesh mesh;

    public MeshData(int chunkSize,Vector3[] vertices,int[] triangles, Vector2[] uvs)
    {
        this.chunkSize = chunkSize;
        this.vertices = vertices;
        this.triangles = triangles;
        this.uvs = uvs;
    }

    public Mesh CreateMesh()
    {
       if(mesh == null) { mesh = new Mesh(); } else { mesh.Clear(); }

        mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.uv = uvs;
        mesh.RecalculateNormals();


        return mesh;
    }
}

And here is my TerrainChunk

    public class TerrainChunk
    {

        GameObject meshObject;
        Vector2 position;
        Bounds bounds;

        MeshRenderer meshRenderer;
        MeshFilter meshFilter;



        public TerrainChunk(Vector2 coord, int chunkSize, Transform parent,Material terrainMaterial)
        {
            position = coord * chunkSize;

            bounds = new Bounds(position, Vector2.one * chunkSize);
            Vector3 positionV3 = new Vector3(position.x , 0, position.y  );
            Debug.Log("CHUNK: COORD"   coord   "POSITION"   position   "POSITION3V"   positionV3);

            meshObject = new GameObject("Terrain Chunk");
            meshFilter = meshObject.AddComponent<MeshFilter>();
            meshRenderer = meshObject.AddComponent<MeshRenderer>();
            meshRenderer.material = terrainMaterial;


            meshObject.transform.position = positionV3;
            meshObject.transform.parent = parent;

            SetVisible(false);

            worldGenerator.RequestMapData(position,OnNoiseDataReceived);

        }
        

        void OnNoiseDataReceived(MapData mapData)
        {
            worldGenerator.RequestMeshData(mapData, OnMeshDataReceived);

        }

        void OnMeshDataReceived(MeshData meshData)
        {
            meshFilter.mesh = meshData.CreateMesh();
        }

        public void UpdateTerrainChunk(Vector2 viewerPosition, int maxRenderDistance)
        {
            float viewerDstFromNearestEdge = Mathf.Sqrt(bounds.SqrDistance(viewerPosition));
            bool visible = viewerDstFromNearestEdge <= maxRenderDistance;
            SetVisible(visible);
        }

        public void SetVisible(bool visible)
        {
            meshObject.SetActive(visible);
        }

        public bool IsVisible()
        {
            return meshObject.activeSelf;
        }
    }
}

CodePudding user response:

If I undestand all your values and variables correctly.

The problem might lay in the Noise Generator.

You need to create the chunkSize to be bigger by 1 so if you are passing 250 you will need to pass 251, as the for loop in the Noise Generator stops at 249 and not 250. (I might be wrong about this ), If you do this the mesh generator will now have the right values for calculation.

So your chunksize variable should look like this

chunkSize = chunkSize   1;

Now there will still be smaller gaps and the mesh will clip through each other, so to fix this you will need to position the Chunk and you do it this way ->

(If your coord serves as a direction in which the chunk will be created from your World generator object -> for example chunks pointing North will be with values x:0 y:1, chunks pointing West will be x:-1 y:0, NorthWest chunks x:-1 y:-1 and so on), you may need to change the 0.5f to your values so the chunks align properly.

Vector3 positionV3 = new Vector3(position.x   (coord.x   0.5f), 0, position.y   (coord.y   0.5f) );

There still may be some smaller gaps visible in the terrain, but this can be fixed by playing with the values, or you can try and access each Chunk and get the edge vertices and their heights and connect the chunks together this way.

  • Related