JinChanChan/Assets/Scripts/Test/TestMesh.cs

66 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
namespace Test
{
[RequireComponent(typeof(MeshFilter)), RequireComponent(typeof(MeshRenderer))]
public class TestMesh : MonoBehaviour
{
Mesh mesh;
private void Awake()
{
mesh = new Mesh();
// 定义顶点数组
List<Vector3> vertices = new List<Vector3>();
// 定义三角形数组,每个三角形由三个顶点的索引组成
List<int> triangles = new List<int>();
List<Color> colors = new List<Color>();
for (int z = 0; z < 3; z++)
{
for (int x = 0; x < 3; x++)
{
var center = new Vector3(
// (x + z * 0.5f - z / 2) x加上z的一半再减去z的一半的整数值
(x + z * 0.5f - z / 2) * (HexMetrics.innerRadius * 2f),
0,
HexMetrics.offset * z);
Color color = new Color(Random.Range(0,1f), Random.Range(0,1f), Random.Range(0,1f), 1);
for (int i = 0; i < 6; i++)
{
var verticesCount = vertices.Count;
vertices.Add(center);
vertices.Add(center + HexMetrics.corners[i]);
vertices.Add(center + HexMetrics.corners[i + 1]);
triangles.Add(verticesCount);
triangles.Add(verticesCount + 1);
triangles.Add(verticesCount + 2);
colors.Add(color);
colors.Add(color);
colors.Add(color);
}
}
}
mesh.vertices = vertices.ToArray();
mesh.colors = colors.ToArray();
mesh.triangles = triangles.ToArray();
// 计算法线
mesh.RecalculateNormals();
GetComponent<MeshFilter>().mesh = mesh;
// 为 MeshRenderer 指定材质
// GetComponent<MeshRenderer>().material = new Material(Shader.Find("Standard"));
}
}
}