I’m trying to generate a mesh from a heightmap, this works fine “The heightmap is different from the biome map, also working on it..” however there is a problem along the width “x axis” where it misses like a quarter of it and starts overlapping the mesh also upside down.
The function is called on start only and honestly i can’t figure this one out,i’ve been comparing with other posts and for some reason have been having the same undesired result.
Assuming the width and height is 300 by 300 here’s the code and some pictures:
void GenerateMesh()
{
GameObject meshObject = GameObject.Find("Mesh");
MeshFilter meshFilter = null;
MeshRenderer meshRenderer = null;
Mesh mesh = null;
if (meshObject == null)
{
meshObject = new GameObject("Mesh");
meshFilter = meshObject.AddComponent<MeshFilter>();
meshRenderer = meshObject.AddComponent<MeshRenderer>();
mesh = new Mesh();
meshFilter.mesh = mesh;
}
else
{
meshFilter = meshObject.GetComponent<MeshFilter>();
meshRenderer = meshObject.GetComponent<MeshRenderer>();
mesh = meshFilter.mesh;
mesh.Clear();
}
List<Vector3> verts = new List<Vector3>();
List<int> tris = new List<int>();
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
// pixels coordinates
float u = i / (float)width;
float v = j / (float)height;
// grayscale value from the height map texture
float grayscaleValue = rawPerlinNoiseTex.GetPixelBilinear(u, v).grayscale;
// vertex position
Vector3 vertexPosition = new Vector3(i, grayscaleValue * 100, j);
verts.Add(vertexPosition);
// checking if it's the last row/column
if (i < width - 1 && j < height - 1)
{
int index = (i * height) + j;
int indexDown = ((i + 1) * height) + j;
// first triangle of the quad
tris.Add(index);
tris.Add(index + 1);
tris.Add(indexDown);
// second triangle of the quad
tris.Add(indexDown);
tris.Add(index + 1);
tris.Add(indexDown + 1);
}
}
}
// uvs
Vector2[] uvs = new Vector2[verts.Count];
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
uvs[(i * height) + j] = new Vector2(i / (float)width, j / (float)height);
}
}
mesh.vertices = verts.ToArray();
mesh.triangles = tris.ToArray();
mesh.uv = uvs;
mesh.RecalculateNormals();
meshRenderer.material.mainTexture = texture;
}