- Home /
Why is this generating flat terrain?
I'm using the following piece of code to generate psuedo-random terrain similar to that in Minecraft.
using UnityEngine;
/// <summary>
/// Terrain generator.
/// </summary>
/// <param name="cube">The cube to instaniate while generating terrain.</param>
/// <param name="noiseScale">The factor to multiply noise height by.</param>
public class TerrainGenerator : MonoBehaviour
{
public GameObject cube;
public int worldWidthX;
public int worldWidthZ;
/// <summary>
/// Generates the terrain.
/// </summary>
public void GenerateTerrain()
{
for(int x = 0; x <= this.worldWidthX; ++x)
{
for(int z = 0; z <= this.worldWidthZ; ++z)
{
float y = Mathf.PerlinNoise(x / 30, 76) * Mathf.PerlinNoise(z / 30, 22) * 40;
Instantiate(this.cube, new Vector3(x, y, z), this.cube.transform.rotation);
}
}
}
void Start()
{
this.GenerateTerrain();
}
}
I'm using the algorithm provided in the answer to this question, but I still get a completely flat result, as seen below:
Can anyone tell my why I'm getting a result like this?
What is the 76 and 22 you have hard coded in there? Perhaps you meant to use something like this?
float y= $$anonymous$$athf.PerlinNoise(x / 30, z / 30) * 40.0f
Answer by Eric5h5 · Aug 08, 2015 at 04:24 AM
You're using integer division; e.g. x/30 will always equal 0 until x is >= 30.
Answer by Positive7 · Aug 08, 2015 at 07:45 AM
Change
float y = Mathf.PerlinNoise(x / 30, 76) * Mathf.PerlinNoise(z / 30, 22) * 40;
to
float y = Mathf.PerlinNoise(x / 30.1f, 76) * Mathf.PerlinNoise(z / 30.1f, 22) * 40;
No need to add an extra 0.1. 30.0f
will also work. For fun, try int x = 1.0f;
. The compiler will loudly tell you that it's a float, even though it has an equivalent int.
Yes 30.0f works too. I just wanted to point him to the right direction and I thought 30.1f is more noticeable .