Skip to content

Instantly share code, notes, and snippets.

@davepape davepape/noiseland2.cs
Last active Nov 6, 2018

Embed
What would you like to do?
Combination of noiseland.cs & noisetex.cs - creates landscape geometry and a texture to apply to the geometry
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class noiseland2 : MonoBehaviour {
public int numRows=10, numCols=10;
public float minX=-1, maxX=1, minY=-1, maxY=1;
public int tex_width=256;
public int tex_height=256;
private Texture2D tex;
private Color32[] colors;
void Start ()
{
generateGeometry();
generateTexture();
}
void generateTexture()
{
tex = new Texture2D(tex_width,tex_height);
colors = new Color32[tex_width*tex_height];
GetComponent<Renderer>().material.mainTexture = tex;
int index = 0;
for (int j=0; j < tex_height; j++)
for (int i=0; i < tex_width; i++)
{
float x = Mathf.Lerp(minX,maxX,i/(tex_width-1f));
float y = Mathf.Lerp(minY,maxY,j/(tex_height-1f));
float h = height(x,y);
if (h < 0.5)
colors[index] = Color.blue;
else if (h < 0.8)
colors[index] = Random.ColorHSV(0.3f,0.35f,0.7f,1f,0.8f,0.9f);
else if (h < 0.95)
colors[index] = Random.ColorHSV(0.15f,0.2f,0.7f,0.8f,0.5f,0.75f);
else
colors[index] = Random.ColorHSV(0f,1f,0f,0.1f,0.9f,1f);
index++;
}
tex.SetPixels32(colors);
tex.Apply();
}
void generateGeometry()
{
int index;
Vector3[] myVerts = new Vector3[numRows*numCols];
Vector2[] myUV = new Vector2[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));
float u = Mathf.Lerp(0,1,i/(numCols-1f));
float v = Mathf.Lerp(0,1,j/(numRows-1f));
myVerts[index] = new Vector3(x,height(x,y),y);
myUV[index] = new Vector2(u,v);
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.uv = myUV;
myMesh.triangles = myTris;
myMesh.RecalculateNormals();
}
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.