Skip to content

Instantly share code, notes, and snippets.

@dav-s
Created November 16, 2018 23:30
Show Gist options
  • Save dav-s/fbb57f1109a589bea9bc9f123677ef88 to your computer and use it in GitHub Desktop.
Save dav-s/fbb57f1109a589bea9bc9f123677ef88 to your computer and use it in GitHub Desktop.
Noise
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Perlin : MonoBehaviour {
// Use this for initialization
void Start () {
GameObject obj = GameObject.Find("Terrain");
if (obj.GetComponent<Terrain>())
{
Terrain terrain = obj.GetComponent<Terrain>();
float[,] heights = new float[terrain.terrainData.heightmapWidth, terrain.terrainData.heightmapHeight];
float tileSize = 10.0f;
print(terrain.terrainData.heightmapWidth);
print(terrain.terrainData.heightmapHeight);
for (int i = 0; i < terrain.terrainData.heightmapWidth; i++)
{
for (int k = 0; k < terrain.terrainData.heightmapHeight; k++)
{
float x = ((float)i / (float)terrain.terrainData.heightmapWidth) * tileSize;
float y = ((float)k / (float)terrain.terrainData.heightmapHeight) * tileSize;
// print(x);
// print(y);
float h = (PerlinNoise.getHeight(x, y) + 1) / 10.0f;
heights[i, k] = h;
}
}
terrain.terrainData.SetHeights(0, 0, heights);
}
}
// Update is called once per frame
void Update () {
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PerlinNoise {
public static float getHeight(float x, float z){
int lowerX = (int)Mathf.Floor(x);
int lowerZ = (int)Mathf.Floor(z);
int upperX = lowerX + 1;
int upperZ = lowerZ + 1;
float offsetX = x - lowerX;
float offsetZ = z - lowerZ;
float lowerLeftGrad = Vector2.Dot(new Vector2(offsetX, offsetZ), getCornerVector(lowerX, lowerZ));
float upperLeftGrad = Vector2.Dot(new Vector2(offsetX, offsetZ - 1), getCornerVector(lowerX, lowerZ + 1));
float upperRightGrad = Vector2.Dot(new Vector2(offsetX - 1, offsetZ - 1), getCornerVector(lowerX + 1, lowerZ + 1));
float lowerRightGrad = Vector2.Dot(new Vector2(offsetX - 1, offsetZ), getCornerVector(lowerX + 1, lowerZ));
float lowerLerp = lerp(lowerLeftGrad, lowerRightGrad, fade(offsetX));
float upperLerp = lerp(upperLeftGrad, upperRightGrad, fade(offsetX));
float totalLerp = lerp(lowerLerp, upperLerp, fade(offsetZ));
return totalLerp;
}
public static float fade(float t){
return t * t * t * (t * (t * 6 - 15) + 10);
}
public static float lerp(float u, float v, float time){
return u * (1 - time) + v * time;
}
public static Vector2 getCornerVector(int x, int y){
int seed = (x ^ (x >> 16)) << 16 | ((y ^ (y >> 16)) & 0xFFFF);
Random.seed = seed;
Vector2 corner = new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f));
corner.Normalize();
return corner;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment