Skip to content

Instantly share code, notes, and snippets.

@poemdexter
Created August 28, 2014 14:24
Show Gist options
  • Save poemdexter/ffa5f397b7a8b3c882bf to your computer and use it in GitHub Desktop.
Save poemdexter/ffa5f397b7a8b3c882bf to your computer and use it in GitHub Desktop.
Make a sweet mesh dawg. Triangles don't share verts.
using System;
using UnityEngine;
using System.Collections;
public class CreateWorldMesh : MonoBehaviour
{
public int dimension;
public void Start()
{
MeshFilter meshFilter = GetComponent<MeshFilter>();
if (meshFilter == null)
{
Debug.LogError("MeshFilter not found!");
return;
}
// create square set of points
Vector3[] points = new Vector3[(int) Math.Pow(dimension + 1, 2)];
//Debug.Log("points length" + points.Length);
// fill set with points
int j = 0;
for (int x = 0; x <= dimension; x++)
{
for (int z = 0; z <= dimension; z++)
{
Debug.Log(j);
points[j] = new Vector3(x, 0, z);
j++;
}
}
// clear the mesh
Mesh mesh = new Mesh();
// create set of verts
Vector3[] verts = new Vector3[6 * (int) Math.Pow(dimension, 2)];
//Debug.Log("verts length" + verts.Length);
// fill set with verts from points
int k = 0;
for (int x = 0; x < dimension; x++)
{
for (int z = 0; z < dimension; z++)
{
// top triangle of quad
//Debug.Log(k + " " + (z + ((x * dimension) + x) + 0));
verts[k] = points[z + ((x * dimension) + x) + 0];
k++;
//Debug.Log(k + " " + (z + ((x * dimension) + x) + 1));
verts[k] = points[z + ((x * dimension) + x) + 1];
k++;
//Debug.Log(k + " " + (z + ((x * dimension) + x) + dimension + 2));
verts[k] = points[z + ((x * dimension) + x) + dimension + 2];
k++;
// bottom triangle of quad
//Debug.Log(k + " " + (z + ((x * dimension) + x) + 0));
verts[k] = points[z + ((x * dimension) + x) + 0];
k++;
//Debug.Log(k + " " + (z + ((x * dimension) + x) + dimension + 2));
verts[k] = points[z + ((x * dimension) + x) + dimension + 2];
k++;
//Debug.Log(k + " " + (z + ((x * dimension) + x) + dimension + 1));
verts[k] = points[z + ((x * dimension) + x) + dimension + 1];
k++;
}
}
// create set of triangles
int[] tris = new int[6 * (int) Math.Pow(dimension, 2)];
for (int i = 0; i < tris.Length; i++)
{
tris[i] = i;
}
// assign everything to mesh
mesh.vertices = verts;
mesh.triangles = tris;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
mesh.Optimize();
meshFilter.mesh = mesh;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment