Skip to content

Instantly share code, notes, and snippets.

@pailhead
Created July 24, 2013 21:38
Show Gist options
  • Save pailhead/6074816 to your computer and use it in GitHub Desktop.
Save pailhead/6074816 to your computer and use it in GitHub Desktop.
generate an ngon mesh in unity
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class ProceduralCircle : MonoBehaviour {
public float radius = 1;
public int sides = 5;
private Vector3[] vertices;
private Vector2[] uv;
// private int numberTriangle;
private int[] tri;
void Start() {
}
void Update(){
//ovo je novi mesh, nista, samo neka vrsta objekta valjda
Mesh circle = new Mesh(); //definisem mesh kao "circle"
GetComponent<MeshFilter>().mesh = circle; //nadjem komponentu 'meshfilter' i dam joj vrednost circle
//definisem broj tacaka
vertices = new Vector3[sides]; //sides je preuzeto spolja, recimo gui
//loop sa kojim prodjem kroz svaku tacku, i postavim je u krug,
for (int i = 0; i < sides; i++){ //ako pocne od 0, sides je na izgled veci, ali posto je manje, a ne manje jednako, zavrsice se na i-1
vertices[i].x = radius * Mathf.Sin(2*Mathf.PI/sides*(i+1));
vertices[i].y = 0;
vertices[i].z = radius * Mathf.Cos(2*Mathf.PI/sides*(i+1));
}
circle.vertices = vertices; //mesh sada ima vertices
int numTri = sides - 2; //broj trouglova je uvek n minus 2
tri = new int[numTri * 3]; //ali broj indecis je veci, za svaki trougao ima 3 tacke, kontam da ima neki fazon sa vektorom3, odnosno da je ovo isto kao unosenje jos jedne tacke
Debug.Log ("The number of triangles is: " + numTri);
//definisati indecis
int k = 0;
int j = 1;
for (int i = 0; i < numTri; i++) {
// Debug.Log ("For " + numTri + " triangles, the loop ran " + (i + 1) + " times." );
// Debug.Log ("For " + numTri + " triangles, the loop ran *add counter*" );
tri[k] = 0; //svaka treca tacka ce biti 0
Debug.Log (tri[i]);
tri[k+1] = j; //sledeca je 1 u prvom loopu, a posle je ono sto dodje sledece
Debug.Log (tri[i+1]);
j++;
// Debug.Log (j);
tri[k+2] = j;
Debug.Log (tri[i+2]);
k+=3;
}
circle.triangles = tri;
//normale
Vector3[] normals = new Vector3[sides];
for (int i = 0; i < sides; i++){
normals[i] = Vector3.up;
}
circle.normals = normals;
uv = new Vector2[sides];
for (int i = 0; i < sides; i++){
uv[i].x = vertices[i].x / radius / 2f + 0.5f;
uv[i].y = vertices[i].x / radius / 2f + 0.5f;
}
circle.uv = uv;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment