using UnityEngine;
using System.Collections;

public class PolygonMaker : MonoBehaviour {

	[SerializeField]
	private int numberOfVertices = 3;

	[SerializeField]
	private Material material;


	private Transform transform;

	// Use this for initialization
	void Start () {

		Mesh mesh = new Mesh();
		float R = 3.0f;

		Vector3[] vertices = new Vector3[numberOfVertices+1];
		vertices[0] = new Vector3(0,0,0);
		for (int i = 0; i < numberOfVertices; i++)
		{
			float fi = i * 360.0f / numberOfVertices;
			float x = R * Mathf.Cos(fi * Mathf.Deg2Rad);
			float y = R * Mathf.Sin(fi * Mathf.Deg2Rad);
			Vector3 vertex = new Vector3(x, y, 0);
			vertices[i+1] = vertex;
		}

		int[] indices = new int[numberOfVertices * 3];
		for (int i = 1; i < numberOfVertices+1; i++)
		{
			indices[(i-1) * 3] = 0;
			indices[(i - 1) * 3 + 1] = i % numberOfVertices + 1;
			indices[(i-1) * 3 + 2] = i;
		}

		mesh.vertices = vertices;
		mesh.triangles = indices;

		GameObject polygon = new GameObject();
		polygon.AddComponent<MeshFilter>();
		polygon.GetComponent<MeshFilter>().mesh = mesh;
		
		polygon.AddComponent<MeshRenderer>();
		polygon.GetComponent<MeshRenderer>().material = material;

		transform = polygon.transform;
	}
	
	// Update is called once per frame
	void Update () 
	{
		Vector3 pos = transform.position;

		float newY = 3 * Mathf.Sin(Time.fixedTime);
		transform.position = new Vector3(pos.x, newY, pos.z);
	}
}
