` 公共课MainLoop:MonoBehaviour {
public float jagginess;
public int patch_segments;
GameObject ter1;
GameObject ter2;
CMesh cmesh1;
CMesh cmesh2;
void Start () {
ter1 = new GameObject();
ter2 = new GameObject();
patch_segments = 64;
jagginess = 1.3f;
cmesh1 = ter1.GetComponent<CMesh>();
cmesh2 = ter2.GetComponent<CMesh>();
}
void Update () {
if (Input.GetKeyDown(KeyCode.Space)) {
cmesh1.init(patch_segments, 0, 0);
cmesh1.applyDiamondSquare(jagginess);
cmesh1.build();
cmesh2.init(patch_segments, 100, 100);
cmesh2.applyDiamondSquare(jagginess);
cmesh2.build();
}
}
} `
和Mesh类:
`
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
//[RequireComponent(typeof(MeshCollider))]
public class CMesh : MonoBehaviour {
Mesh mesh;
Texture2D heightMap;
float x_pos;
float z_pos;
int segments;
public Vector3 scaleSegments = new Vector3(200, 100, 200);
Vector3 vertex;
Vector3[] vertices;
Vector3[] normals;
Vector2[] uv;
int[] triangles;
Vector3 camera_position;
public void init(int mesh_segments, float position_x, float position_z) {
x_pos = position_x;
z_pos = position_z;
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh = new Mesh();
mesh.name = "Star Mesh";
//camera_position = GameObject.Find ("Main Camera").GetComponent<cameraMovement>().camera_pos;
//scaleSegments = new Vector3(200, 100, 200);
segments = mesh_segments;
initHeightMap();
}
public void build() {
int x, z;
int vsize_x = segments+1;
int vsize_z = segments+1;
int numVerts = vsize_x*vsize_z;
int numQuads = segments*segments;
int numTriangles = numQuads*2;
vertices = new Vector3[numVerts];
normals = new Vector3[numVerts];
uv = new Vector2[numVerts];
triangles = new int[numTriangles*3];
Vector2 uvScale = new Vector2(1.0f/(vsize_x - 1), 1.0f/(vsize_z - 1));
Vector3 vertsScale = new Vector3(scaleSegments.x / (vsize_x - 1), scaleSegments.y, scaleSegments.z / (vsize_z - 1));
//Build vertices, normals and uv's
for (z = 0; z < vsize_z; z++) {
for (x = 0; x < vsize_x; x++) {
vertex = Vector3.Scale(vertsScale, new Vector3(x_pos + x, heightMap.GetPixel(x, z).r, z_pos + z));
vertices [z*vsize_x + x] = vertex + new Vector3(x_pos, 0, z_pos);
normals [z*vsize_x + x] = Vector3.up;
uv [z*vsize_x + x] = Vector2.Scale(new Vector2(x, z), uvScale);
}
}
//Build triangles
int index = 0;
for (z = 0; z < vsize_z - 1; z++) {
for (x = 0; x < vsize_x - 1; x++) {
triangles[index++] = (z * vsize_x) + x;
triangles[index++] = ((z+1) * vsize_x) + x;
triangles[index++] = (z * vsize_x) + x + 1;
triangles[index++] = ((z+1) * vsize_x) + x;
triangles[index++] = ((z+1) * vsize_x) + x + 1;
triangles[index++] = (z * vsize_x) + x + 1;
}
}
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.normals = normals;
mesh.uv = uv;
//MeshFilter mesh_filter = GetComponent<MeshFilter>();
//MeshRenderer mesh_renderer = GetComponent<MeshRenderer>();
//MeshCollider mesh_collider = GetComponent<MeshCollider>();
//mesh_filter.mesh = mesh;
}
`