Skip to content

Instantly share code, notes, and snippets.

@davepape
Last active November 6, 2018 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davepape/b43f7f6f66ee0e5466b4649b972b8d31 to your computer and use it in GitHub Desktop.
Save davepape/b43f7f6f66ee0e5466b4649b972b8d31 to your computer and use it in GitHub Desktop.
Create a fractal landscape by combining different frequencies of Perlin noise
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class noiseland : MonoBehaviour {
public int numRows=10, numCols=10;
public float minX=-1, maxX=1, minY=-1, maxY=1;
float height(float x, float y)
{
x -= minX;
y -= minY;
float h = 0;
float f = 1, s = 1;
for (int i=0; i < 8; i++)
{
h += s * Mathf.PerlinNoise(f*x, f*y);
f *= 2f;
s /= 3f;
}
return h;
}
void Start ()
{
int index;
Vector3[] myVerts = new Vector3[numRows*numCols];
index = 0;
for (int j=0; j < numRows; j++)
for (int i=0; i < numCols; i++)
{
float x = Mathf.Lerp(minX,maxX,i/(numCols-1f));
float y = Mathf.Lerp(minY,maxY,j/(numRows-1f));
myVerts[index] = new Vector3(x,height(x,y),y);
index++;
}
int[] myTris = new int[(numRows-1)*(numCols-1)*2*3];
index = 0;
for (int j=0; j < numRows-1; j++)
for (int i=0; i < numCols-1; i++)
{
myTris[index++] = i + j*numCols;
myTris[index++] = i + (j+1)*numCols;
myTris[index++] = (i+1) + j*numCols;
myTris[index++] = i + (j+1)*numCols;
myTris[index++] = (i+1) + (j+1)*numCols;
myTris[index++] = (i+1) + j*numCols;
}
Mesh myMesh = gameObject.GetComponent<MeshFilter>().mesh;
myMesh.Clear();
myMesh.vertices = myVerts;
myMesh.triangles = myTris;
myMesh.RecalculateNormals();
}
void Update ()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment