I am trying to set the terrain's heights data at runtime with a simplex noise function, while stumbling with converting the local position of the vertices to global position to use as input to keep the simplex noise continuous.
At this time I am setting up multiple terrains tiles, which I added in the editor.
The UnityEngine.Terrain
has a size of 1000 units on x and z and a (default) heightmap resolution of 513.
My actual question is; What am I missing?
I have the impression that next I should convert the vertex position of one terrain to a world position, so the tiles would be seamless, but the result shows a difference at the borders. The simplex noise function has been tested and is correct.
private Vector3 toGlobal(Vector3 position, UnityEngine.Terrain terrain)
{
int res = terrain.terrainData.heightmapResolution;
Vector3 size = terrain.terrainData.size;
Vector3 global = new Vector3( position.x / res * size.x, 0, position.z / res * size.z);
global += terrain.transform.position;
return global;
}
And less interesting, how I use it:
// Get all terrain tiles and cycle through them
UnityEngine.Terrain[] terrains = Resources.FindObjectsOfTypeAll(typeof(UnityEngine.Terrain)) as UnityEngine.Terrain[];
foreach(UnityEngine.Terrain terrain in terrains)
{
int res = terrain.terrainData.heightmapResolution;
float[,] heights = new float[res, res];
float height = 0;
for (int z = 0; z < res; ++z)
{
for (int x = 0; x < res; ++x)
{
Vector3 v = toGlobal(new Vector3(x, 0, z), terrain);
height = (float)(simplex.Noise(v.x * 0.0001, v.z * 0.0001, 0) + 1) * 0.5);
heights[x, z] = height;
}
}
terrain.terrainData.SetHeights(0, 0, heights);
}