- Home /
 
I would like to generate a plane and add hills to it. What would be the correct math for this?
I have the code for a basic grid in Unity that generates a set of vertices. That much of this works, however I'd like to also create dips and hills in the surface. I've tried altering the y property, however that's causing things to go rather weird. This is the code I have so far.
     void Start () {
         vertices = new Vector3[(xSize + 1) * (ySize + 1)];
         for (int i = 0, y = 0; y <= ySize; y++, i++)
         {
             for (int x = 0; x <= xSize; x++)
             {
                 vertices[i] = new Vector3(x, i + y, y);
             }
         }
     }
 
               When I alter the Y, it causes everything to go.... screwy. Sometimes all vertices to the left, others all to the right. How can I correct the math to generate smooth random hills? (Ignoring the i/y, which is just testing to try to get the generation working, however where I thought the code for the displacement would go).
Answer by jdean300 · Aug 27, 2016 at 05:58 AM
Generation of random hills is usually done through multiple layers (usually using Fractal Brownian Motion) of Perlin/Simplex noise. Those would give you a float[,] which you could then apply to an array of vertices like so:
 Vector3[] vertices = new Vector3[xSize * ySize];
 float[,] noise = GetNoise(); //use perlin/simplex noise
 
 for (var j = 0; j < ySize; j++){
     for (var i = 0; i < xSize; i++){
          vertices[i + (j * xSize)] = new Vector3(i, noise[i,j], j);
     }
 }
 
 
               The actual generation of perlin/simplex noise is fairly complex but there are a lot of resources online.
How would I best restrict this to a single direction, horizontal or vertical in order to create the effect of rolling hills? The goal would be to produce a head on effect of travelling over slopes as in a skiing game.
you can use $$anonymous$$athf.PerlinNoise for the noise so something like
 vertices[i + j * xSize] = new Vector3(i,  $$anonymous$$athf.PerlinNoise(i, 0) * amplitude, 0);
 
                 Thank you! This is perfect. I was following the catlikecoding tutorial, but wanted to change the generator some. However, after that.... I got a bit lost in the proper coordinate math.
Your answer