So I’m currently generating a mesh based off a heightmap, and then I want to uv the mesh so that the heightmap texture is aligned with the created mesh.
I’ve been using
uvs.Add(new Vector2(Startx+i / ((float)texture.width), Starty+j / ((float)texture.height)));
But it is displaying the same area of the texture on all the meshes, insead of the respective arean on each of them.
Here is my full script:
public Texture2D hMap;
public Material mat;
//public int ErrorMargin = 10;
void Start(){
int twofifty = hMap.width / 2;
int twofifty2 = hMap.height / 2;
for (int cy = 0; cy < hMap.height; cy = cy + twofifty2) {
for (int cx = 0; cx < hMap.width; cx = cx + twofifty) {
Debug.Log ("x:" + cx + " y:" + cy + " - width:" + twofifty + " height:" + twofifty2);
CreateMesh(hMap, cx, cy, twofifty, twofifty);
}
}
}
void CreateMesh(Texture2D texture, int Startx, int Starty, int Width, int Height){
if (Width > 250 && Height > 250)
return;
List<Vector3> verts = new List<Vector3>();
List<int> tris = new List<int>();
List<Vector2> uvs = new List<Vector2>();
if (Startx + Width > texture.width)
Width = texture.width - Startx;
if (Starty + Height > texture.height)
Height = texture.height - Starty;
//uses 0x0 as the zero "no data" value
//float zero = texture.GetPixel (0, 0).grayscale * 100;
//Bottom left section of the map, other sections are similar
for(int i = 0; i < Width; i++)
{
for(int j = 0; j < Height; j++)
{
float y = texture.GetPixel(Startx+i,Starty+j).grayscale * 100;
//Add each new vertex in the plane
verts.Add(new Vector3(i, y, j));
uvs.Add(new Vector2(Startx+i / ((float)texture.width), Starty+j / ((float)texture.height)));s
//Skip if a new square on the plane hasn't been formed
if (i == 0 || j == 0) continue;
//if (texture.GetPixel(Startx+i,Starty+j) == Color.black || y < zero + ErrorMargin) continue;
//Adds the index of the three vertices in order to make up each of the two tris
tris.Add(Width * i + j); //Top right
tris.Add(Width * i + j - 1); //Bottom right
tris.Add(Width * (i - 1) + j - 1); //Bottom left - First triangle
tris.Add(Width * (i - 1) + j - 1); //Bottom left
tris.Add(Width * (i - 1) + j); //Top left
tris.Add(Width * i + j); //Top right - Second triangle
}
}
GameObject plane = new GameObject("ProcPlane"); //Create GO and add necessary components
plane.AddComponent<MeshFilter>();
MeshRenderer renderer = plane.AddComponent<MeshRenderer>() as MeshRenderer;
renderer.material = mat;
Mesh procMesh = new Mesh();
procMesh.vertices = verts.ToArray(); //Assign verts, uvs, and tris to the mesh
procMesh.uv = uvs.ToArray();
procMesh.triangles = tris.ToArray();
procMesh.RecalculateNormals(); //Determines which way the triangles are facing
plane.GetComponent<MeshFilter>().mesh = procMesh; //Assign Mesh object to MeshFilter
plane.transform.position = new Vector3 (Startx-1, 0, Starty-1);
}