using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//网格创建差不多分这几步: 1,确认顶点 2,确认顶点顺序 3,确认法线,uv...
public class MeshStudy : MonoBehaviour
{
public float sideLength = 2;
public float angleDegree = 100;
private static readonly int ANGLE_DEGREE_PRECISION = 1000;
private static readonly int SIDE_LENGTH_PRECISION = 1000;
private MeshFilter _meshFilter;
private TriangleMeshCreator creator = new TriangleMeshCreator();
//在编辑器中执行
[ExecuteInEditMode]
private void Awake()
{
_meshFilter = GetComponent<MeshFilter>();
}
private void Update() {
_meshFilter.mesh = creator.CreateMesh(sideLength,angleDegree);
}
//在没选中的时候 画出的网格设置为灰色
void OnDrawGizmos() {
Gizmos.color = Color.gray;
DrawMesh();
}
void OnDrawGizmosSelected() {
Gizmos.color = Color.green;
DrawMesh();
}
void DrawMesh() {
Mesh mesh = creator.CreateMesh(sideLength,angleDegree);
int[] tris = mesh.triangles;
//绘制三角形 网格信息是从本地坐标获取的 若在正确的世界位置显示需求转换到世界坐标系
Gizmos.DrawLine(Transform2World(mesh.vertices[0]), Transform2World(mesh.vertices[1]));
Gizmos.DrawLine(Transform2World(mesh.vertices[1]), Transform2World(mesh.vertices[2]));
Gizmos.DrawLine(Transform2World(mesh.vertices[2]), Transform2World(mesh.vertices[0]));
}
private Vector3 Transform2World(Vector3 src) {
return transform.TransformPoint(src);
}
private class TriangleMeshCreator
{
private float _sideLength;
private float _angleDegree;
private Mesh _cacheMesh;
public Mesh CreateMesh(float sideLength, float angleDegree)
{
if (checkDiff(sideLength, angleDegree)) {
Mesh newMesh = Create(sideLength,angleDegree);
if (newMesh != null) {
_cacheMesh = newMesh;
this._sideLength = sideLength;
this._angleDegree = angleDegree;
}
}
return _cacheMesh;
}
//三角形边长和弧长
private Mesh Create(float sideLength, float angleDegree)
{
Mesh mesh = new Mesh();
Vector3[] verticles = new Vector3[3];
//圆的周长为2ΠR 所以弧长 = (n°/360)*2ΠR (简化后: L = n°ΠR/180)
//从弧度转化到角度
float angle = Mathf.Deg2Rad * angleDegree;
float halfAngle = angle / 2;
float cosA = Mathf.Cos(halfAngle);
float sinA = Mathf.Sin(halfAngle);
//随便画一个三角形
verticles[0] = Vector3.zero;
verticles[1] = new Vector3(cosA * sideLength, 0, sinA * sideLength);
verticles[2] = new Vector3(cosA * sideLength, 0, -sinA * sideLength);
//输入网格的顶点和顶点顺序
int[] triangles = new int[3] { 0, 1, 2 };
mesh.vertices = verticles;
mesh.triangles = triangles;
//设置uv顶点信息
Vector2[] uvs = new Vector2[verticles.Length];
//设置如下贴图中就避开了数字 说明uv的对角线坐标分别对应 (0,0) 和 (1,1)
uvs[0] = new Vector2(0, 0.5f);
uvs[1] = new Vector2(0.5f, 0.5f);
uvs[2] = new Vector2(0.6f, 0);
//uvs[0] = new Vector2(0, 0.5f);
//uvs[1] = Vector2.one;
//uvs[2] = Vector2.right;
mesh.uv = uvs;
return mesh;
}
//检测是否满足构成条件
private bool checkDiff(float sideLength, float angleDegree)
{
return (int)((sideLength - this._sideLength) * SIDE_LENGTH_PRECISION) != 0 ||
(int)((angleDegree - this._angleDegree) * ANGLE_DEGREE_PRECISION) != 0;
}
}
}
原创地址:https://www.cnblogs.com/JLZT1223/p/6085339.html