Skip to content

Instantly share code, notes, and snippets.

@yat1ma30
Last active May 2, 2018 14:33
Show Gist options
  • Save yat1ma30/1312474cd897d4ad296ffca752a5f387 to your computer and use it in GitHub Desktop.
Save yat1ma30/1312474cd897d4ad296ffca752a5f387 to your computer and use it in GitHub Desktop.
Perlin noise in Unity (from this tutorial https://youtu.be/f6cAAjMfPs8) // modified
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GenerateWaveScript : MonoBehaviour {
[Range(0.1f, 20.0f)]
public float heightScale = 5.0f;
[Range(0.1f, 40.0f)]
public float detailScale = 5.0f;
private Mesh myMesh;
private Vector3[] vertices;
private void Update()
{
GenerateWave();
}
void GenerateWave() {
myMesh = this.GetComponent<MeshFilter>() .mesh;
vertices = myMesh.vertices;
int counter = 0;
int yLevel = 0;
for (int i = 0; i < 11; i++)
{
for (int j = 0; j < 11; j++) {
CalculationMethod(counter, yLevel);
counter++;
}
yLevel++;
}
myMesh.vertices = vertices;
myMesh.RecalculateBounds();
myMesh.RecalculateNormals();
Destroy(gameObject.GetComponent<MeshCollider>());
MeshCollider collider = gameObject.AddComponent<MeshCollider>();
collider.sharedMesh = null;
collider.sharedMesh = myMesh;
}
public bool waves = false;
public float wavesSpeed = 5.0f;
void CalculationMethod(int i, int j) {
Vector3 p = this.transform.TransformPoint(vertices[i]);
if (waves) {
vertices[i].z = Mathf.PerlinNoise(
Time.time / wavesSpeed + p.x / detailScale,
Time.time / wavesSpeed) * heightScale;
vertices[i].z -= j;
} else {
vertices[i].z = Mathf.PerlinNoise(
p.x / detailScale,
0) * heightScale;
vertices[i].z -= j;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment