Created
March 20, 2019 06:45
-
-
Save gemfile0/2f1bc2d5a6e4a9481ece18e72c901f12 to your computer and use it in GitHub Desktop.
Excerpt from Brackeys video tutorial.
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 UnityEngine; | |
[RequireComponent(typeof(MeshFilter))] | |
public class MeshGenerator : MonoBehaviour | |
{ | |
public int xSize = 20; | |
public int zSize = 20; | |
Mesh mesh; | |
Vector3[] vertices; | |
int[] triangles; | |
#region Unity Method | |
void Start() | |
{ | |
mesh = new Mesh(); | |
GetComponent<MeshFilter>().mesh = mesh; | |
CreateShape(); | |
UpdateMesh(); | |
} | |
#endregion | |
#region Editor Method | |
void OnDrawGizmos() | |
{ | |
if (vertices == null) return; | |
for (int i = 0; i < vertices.Length; i++) | |
{ | |
Gizmos.DrawSphere(vertices[i], .1f); | |
} | |
} | |
#endregion | |
#region Custom Method | |
void CreateShape() | |
{ | |
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) * 2f; | |
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(); | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment