-
Notifications
You must be signed in to change notification settings - Fork 1
/
MeshGeneratorWithPerlin.cs
76 lines (64 loc) · 2.12 KB
/
MeshGeneratorWithPerlin.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MeshGeneratorWithPerlin : MonoBehaviour
{
[SerializeField] private int myXLength;
[SerializeField] private int myZLength;
private Mesh myMesh;
private Vector3[] myVertices;
private int[] myTriangles;
private MeshFilter myMeshFilter;
private MeshCollider myMeshCollider;
private void Awake()
{
myMeshFilter = GetComponent<MeshFilter>();
myMeshCollider = gameObject.AddComponent<MeshCollider>();
myMeshCollider.sharedMesh = null;
myMesh = new Mesh();
myMeshFilter.mesh = myMesh;
}
private void Start()
{
GenerateMesh();
SetMesh();
}
private void GenerateMesh()
{
myVertices = new Vector3[(myXLength + 1) * (myZLength + 1)];
for (int zLength = 0, index = 0; zLength <= myZLength; zLength++)
{
for (int xLength = 0; xLength <= myZLength; xLength++)
{
float y = Mathf.PerlinNoise(xLength * 0.3f, zLength * 0.3f) * 2.0f;
myVertices[index] = new Vector3(xLength, y, zLength);
index++;
}
}
int vertex = 0;
int triangles = 0;
myTriangles = new int[myXLength * myZLength * 6];
for (int zLength = 0; zLength < myZLength; zLength++)
{
for (int xLength = 0; xLength < myXLength; xLength++)
{
myTriangles[triangles + 0] = vertex + 0;
myTriangles[triangles + 1] = vertex + myXLength + 1;
myTriangles[triangles + 2] = vertex + 1;
myTriangles[triangles + 3] = vertex + 1;
myTriangles[triangles + 4] = vertex + myXLength + 1;
myTriangles[triangles + 5] = vertex + myXLength + 2;
vertex++;
triangles += 6;
}
vertex++;
}
}
private void SetMesh()
{
myMesh.vertices = myVertices;
myMesh.triangles = myTriangles;
myMesh.RecalculateBounds();
myMeshCollider.sharedMesh = myMesh;
}
}