Created
November 1, 2018 17:27
-
-
Save davepape/17236ef49ab48d1c437add26ec5acbe8 to your computer and use it in GitHub Desktop.
Create a fractal landscape mesh in Unity3D, using midpoint subdivision
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class fractalland : MonoBehaviour { | |
Vector3[][] newArray(int size) | |
{ | |
Vector3[][] v = new Vector3[size][]; | |
for (int i=0; i < size; i++) | |
v[i] = new Vector3[size]; | |
return v; | |
} | |
float heightOffset(float yscale) | |
{ | |
return (Random.Range(-yscale,yscale) + Random.Range(-yscale,yscale) + Random.Range(-yscale,yscale))/3f; | |
} | |
void Start () | |
{ | |
Vector3[][] verts0; | |
int size = 2, size0, i, j; | |
float yscale = 10f; | |
Vector3[][] verts = newArray(2); | |
verts[0][0] = new Vector3(-10,0,-10); | |
verts[1][0] = new Vector3(10,0,-10); | |
verts[0][1] = new Vector3(-10,0,10); | |
verts[1][1] = new Vector3(10,0,10); | |
for (int level=0; level < 3; level++) | |
{ | |
verts0 = verts; | |
size0 = size; | |
size = size * 2 - 1; | |
verts = newArray(size); | |
yscale /= 1.8f; | |
for (i=0; i < size0; i++) | |
for (j=0; j < size0; j++) | |
{ | |
verts[i*2][j*2] = verts0[i][j]; | |
} | |
for (j=0; j < size0; j++) | |
for (i=0; i < size0-1; i++) | |
{ | |
Vector3 v = (verts0[i][j] + verts0[i+1][j])/2; | |
v.y += heightOffset(yscale); | |
verts[i*2+1][j*2] = v; | |
} | |
for (i=0; i < size0; i++) | |
for (j=0; j < size0-1; j++) | |
{ | |
Vector3 v = (verts0[i][j] + verts0[i][j+1])/2; | |
v.y += heightOffset(yscale); | |
verts[i*2][j*2+1] = v; | |
} | |
for (i=0; i < size0-1; i++) | |
for (j=0; j < size0-1; j++) | |
{ | |
Vector3 v = (verts0[i][j] + verts0[i+1][j] + verts0[i][j+1] + verts0[i+1][j+1])/4; | |
v.y += heightOffset(yscale); | |
verts[i*2+1][j*2+1] = v; | |
} | |
} | |
Vector3[] myVerts = new Vector3[size*size]; | |
for (i=0; i < size; i++) | |
for (j=0; j < size; j++) | |
{ | |
myVerts[i+j*size] = verts[i][j]; | |
} | |
int[] myTris = new int[(size-1)*(size-1)*2*3]; | |
int index = 0; | |
for (j=0; j < size-1; j++) | |
for (i=0; i < size-1; i++) | |
{ | |
myTris[index++] = i + j*size; | |
myTris[index++] = i + (j+1)*size; | |
myTris[index++] = (i+1) + j*size; | |
myTris[index++] = i + (j+1)*size; | |
myTris[index++] = (i+1) + (j+1)*size; | |
myTris[index++] = (i+1) + j*size; | |
} | |
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