using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class YuanZhu : MonoBehaviour
{
public MeshFilter meshFilter;
public MeshRenderer meshRenderer;
public int num = 10;//角的数量
public float r = 10;
public Texture texture;
public Action<float> action;
public void SetAction(Action<float> action)
{
this.action = action;
}
// Start is called before the first frame update
void Start()
{
meshFilter = gameObject.AddComponent<MeshFilter>();
meshRenderer = gameObject.AddComponent<MeshRenderer>();
gameObject.AddComponent<BoxCollider>();
Mesh mesh = new Mesh();
VertexHelper vh = new VertexHelper();
//添加圆心
vh.AddVert(Vector3.up, Color.white, new Vector2(0.5f, 0.5f));
//计算每个角的弧度
float ang = (2 * Mathf.PI) / num;
//存储上盖顶点坐标
List<Vector3> upv = new List<Vector3>();
for (int i = 0; i < num; i++)
{
float x = Mathf.Sin(i * ang) * r;//Sin算x;
float z = Mathf.Cos(i * ang) * r;//Cos算y;
float uvx = (x + r) / (2 * r);//算UVx点
float uvy = (z + r) / (2 * r);//算UVy点
vh.AddVert(new Vector3(x, 1, z), Color.white, new Vector2(uvx, uvy));
upv.Add(new Vector3(x, 1, z));
//添加绘制
if (i == 0)
{
vh.AddTriangle(0, num, 1);
}
else
{
vh.AddTriangle(0, i, i + 1);
}
}
//前面上盖已经用过Num+1个顶点了不能再用了
int after = num + 1;
//下盖
//存储下盖顶点坐标
List<Vector3> downv = new List<Vector3>();
//添加圆心
vh.AddVert(Vector3.down, Color.white, new Vector2(0.5f, 0.5f));
for (int i = 0; i < num; i++)
{
float x = Mathf.Sin(i * ang) * r;//Sin算x;
float z = Mathf.Cos(i * ang) * r;//Cos算y;
float uvx = (x + r) / (2 * r);//算UVx点
float uvy = (z + r) / (2 * r);//算UVy点
vh.AddVert(new Vector3(x, -1, z), Color.white, new Vector2(uvx, uvy));
downv.Add(new Vector3(x, -1, z));
//添加绘制
if (i == 0)
{
vh.AddTriangle(0 + after, 1 + after, num + after);
}
else
{
vh.AddTriangle(0 + after, i + 1 + after, i + after);
}
}
//画边
//上盖和下盖用过的不能再用
int after2 = (num + 1) * 2;
for (int i = 0; i < num; i++)
{
vh.AddVert(downv[i], Color.white, new Vector2((float)i / (float)num, 0));
vh.AddVert(upv[i], Color.white, new Vector2((float)i / (float)num, 1));
//添加完一圈再补充两个,让边闭合
if (i == num - 1)
{
vh.AddVert(downv[0], Color.white, new Vector2(1, 0));
vh.AddVert(upv[0], Color.white, new Vector2(1, 1));
}
vh.AddTriangle(i * 2 + after2, (i + 1) * 2 + 1 + after2, i * 2 + 1 + after2);
vh.AddTriangle(i * 2 + after2, (i + 1) * 2 + after2, (i + 1) * 2 + 1 + after2);
}
//顶点助手转网格
vh.FillMesh(mesh);
mesh.RecalculateNormals();
gameObject.GetComponent<MeshFilter>().mesh = mesh;
Material material = new Material(Shader.Find("Standard"));
material.mainTexture = texture;
gameObject.GetComponent<MeshRenderer>().material = material;
// Update is called once per frame
void Update()
{
}
}