Skip to content

Instantly share code, notes, and snippets.

@Finkes
Created October 11, 2019 21:03
Show Gist options
  • Save Finkes/16ad26a6a0c3475bc4118657d67571a3 to your computer and use it in GitHub Desktop.
Save Finkes/16ad26a6a0c3475bc4118657d67571a3 to your computer and use it in GitHub Desktop.
Procedural Terrain for Unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProceduralTerrain : MonoBehaviour
{
Vector3[] vertices;
int[] triangles;
Mesh mesh;
public int xSize = 20;
public int zSize = 20;
MeshCollider meshCollider;
float timer = 0f;
bool done = false;
// Start is called before the first frame update
void Start()
{
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
meshCollider = gameObject.AddComponent<MeshCollider>();
CreateShape(0f);
UpdateMesh();
}
void CreateShape(float h){
vertices = new Vector3[(xSize+1) * (zSize +1)];
int i = 0;
for(int z=0; z <= zSize; z++){
for(int x=0; x <= xSize; x++){
float y = Mathf.PerlinNoise(x*.3f, z*.3f) * h;
vertices[i] = new Vector3(x,y,z);
i++;
}
}
triangles = new int[xSize * zSize * 6];
int vert = 0;
int tris = 0;
for(int z=0; z< zSize; z++){
for(int x=0; x < xSize; x++){
triangles[tris + 0] = vert + 0;
triangles[tris + 1] = vert + xSize + 1;
triangles[tris + 2] = vert + 1;
triangles[tris + 3] = vert + 1;
triangles[tris + 4] = vert + xSize + 1;
triangles[tris + 5] = vert + xSize + 2;
vert++;
tris += 6;
}
vert++;
}
}
void UpdateMesh(){
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.RecalculateNormals();
// update collider?
meshCollider.sharedMesh = mesh;
}
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
if(timer > 10f){
CreateShape(0f);
UpdateMesh();
}
else if(timer > 5f){
done = true;
CreateShape(2f);
UpdateMesh();
}
}
void OnDrawGizmos(){
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment