using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CreatCylinder : MonoBehaviour
{
public int n = 6;
public float r = 5;
// Start is called before the first frame update
void Start()
{
//创建一个网格
Mesh mesh = new Mesh();
//顶点助手
VertexHelper vh = new VertexHelper();
//圆柱4个面组成
//这是圆柱上下圆的每个角弧度
float ang = 2 * Mathf.PI / n;
//第一个面(上面的圆盖)
//上圆的顶点
vh.AddVert(new Vector3(0, 1, 0), Color.blue, new Vector2(0.5f, 0.5f));
for (int i = 0; i < n; i++)
{
//通过正弦和余弦函数计算顶点的坐标
float x = Mathf.Sin(ang * i) * r;
float y = Mathf.Cos(ang * i) * r;
//计算uv坐标
float uvx = (x + r) / (r + r);
float uvy = (y + r) / (r + r);
//添加顶点
vh.AddVert(new Vector3(x, 1, y), Color.white, new Vector2(uvx, uvy));
//绘制上圆
if (i == 0)
{
vh.AddTriangle(0, n, 1);
}
else
{
vh.AddTriangle(0, i, i + 1);
}
}
//用过的顶点不再使用
int next = 1 + n; ;
//下面的圆
vh.AddVert(new Vector3(0, -1, 0), Color.blue, new Vector2(0.5f, 0.5f));
for (int i = 0; i < n; i++)
{
//通过正弦和余弦函数计算顶点的坐标
float x = Mathf.Sin(ang * i) * r;
float y = Mathf.Cos(ang * i) * r;
//计算uv坐标
float uvx = (x + r) / (r + r);
float uvy = (y + r) / (r + r);
//添加顶点
vh.AddVert(new Vector3(x, -1, y), Color.white, new Vector2(uvx, uvy));
//绘制下圆
if (i == 0)
{
vh.AddTriangle(0+next, 1 + next, n + next);
}
else
{
vh.AddTriangle(0 + next, i + 1 + next, i + next);
}
}
//用过的顶点再使用
next = (1 + n) * 2;
//圆柱侧面
for (int i = 0; i < n+1; i++)
{
//计算顶点坐标
float x = Mathf.Sin(ang * i) * r;
float y = Mathf.Cos(ang * i) * r;
//计算uv坐标(这个n除以几就是要把侧面贴图分几份)
float uvx = (float)i / ((float)n / 2);
//计算最后一个的坐标
if(i==n)
{
x = Mathf.Sin(ang * 0) * r;
y = Mathf.Cos(ang * 0) * r;
}
//添加顶点
vh.AddVert(new Vector3(x, 1, y), Color.white, new Vector2(uvx, 0));
vh.AddVert(new Vector3(x, -1, y), Color.white, new Vector2(uvx, 1));
}
//绘制图形
//+next是为了绘制时跳过使用过的顶点
for (int i = 0; i < n; i++)
{
vh.AddTriangle(i * 2 + next, i * 2 + 1 + next, (i + 1) * 2 + 1 + next);
vh.AddTriangle(i * 2 + next, (i + 1) * 2 + 1 + next, (i + 1) * 2 + next);
}
//顶点助手数据放到网格上
vh.FillMesh(mesh);
//自动计算法线(也可以说是添加棱角)
mesh.RecalculateNormals();
//mesh网格赋值给网格过滤器
GetComponent<MeshFilter>().mesh = mesh;
}
// Update is called once per frame
void Update()
{
}
}