I have a weird problem. At the moment I am doing a selfmade Terrain generator, for now I am doing a "plane" generation only for the bottom area with flat surface. My problem is that when I set terrainSize
too high the triangles starts overlapping ironically.
Here is a picture when i set terrainSize
to 120:
Here is a picture when i set the terrainSize
to 200:
At the size 200 looks like its overlapping twice, i found out that the max terrainSize
for me is 114 at 115 it starts overlapping.
Here is my code, maybe you can find something out and help me and other on this platform:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
public class MeshGeneratorSecond : MonoBehaviour
{
[SerializeField] private int terrainSize;
private Mesh myMesh;
private Vector3[] vertices;
private int[] triangles;
private int verticesInVertex = 5;
private int trianglesInVertex = 4;
void Start()
{
myMesh = new Mesh();
GetComponent<MeshFilter>().mesh = myMesh;
vertices = new Vector3[terrainSize * terrainSize * 5];
triangles = new int[terrainSize * terrainSize * 12];
StartCoroutine(CreateShape());
}
IEnumerator CreateShape()
{
int vertex = 0;
int triangle = 0;
for(int x = 0; x < terrainSize; x++)
{
for(int z = 0; z < terrainSize; z++)
{
vertices[vertex] = new Vector3(x, 0, z);
vertices[vertex + 1] = new Vector3(x, 0, z + 1);
vertices[vertex + 2] = new Vector3(x + 1, 0, z + 1);
vertices[vertex + 3] = new Vector3(x + 1, 0, z);
vertices[vertex + 4] = new Vector3(x + 0.5f, 0, z + 0.5f);
//First Triangle
triangles[triangle] = vertex;
triangles[triangle + 1] = vertex + 1;
triangles[triangle + 2] = vertex + 4;
//Second Triangle
triangles[triangle + 3] = vertex + 1;
triangles[triangle + 4] = vertex + 2;
triangles[triangle + 5] = vertex + 4;
//Third Triangle
triangles[triangle + 6] = vertex + 2;
triangles[triangle + 7] = vertex + 3;
triangles[triangle + 8] = vertex + 4;
//Fourth Triangle
triangles[triangle + 9] = vertex + 3;
triangles[triangle + 10] = vertex;
triangles[triangle + 11] = vertex + 4;
vertex += verticesInVertex;
triangle += trianglesInVertex * 3;
}
UpdateMesh();
yield return new WaitForSeconds(.1f);
}
}
private void UpdateMesh()
{
myMesh.Clear();
myMesh.vertices = vertices;
myMesh.triangles = triangles;
myMesh.RecalculateNormals();
}
public void OnDrawGizmos()
{
Gizmos.color = Color.red;
for(int i = 0; i < vertices.Length; i++)
{
Gizmos.DrawSphere(vertices[i], .1f);
}
}
}