(二)平面plane
概述
本文用来实现一个平面plane,其与四顶点的四边形mesh相比,网格变多。
Mesh代码
基类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter),typeof(MeshRenderer))]
public class CreateMeshBase : MonoBehaviour
{
MeshFilter meshFilter;
protected Mesh mesh;
protected virtual Vector3[] Vertices { get; }
protected virtual int[] Triangles { get; }
protected virtual Vector3[] Normals { get; }
protected virtual Vector2[] Uvs { get; }
protected virtual string MeshName { get; }
protected virtual void Start()
{
GetMeshFilter();
}
protected virtual void Reset()
{
GetMeshFilter();
}
protected virtual void OnValidate()
{
GetMeshFilter();
}
void GetMeshFilter()
{
if (meshFilter == null)
{
meshFilter = GetComponent<MeshFilter>();
mesh = new Mesh();
}
mesh.triangles = null;
mesh.uv = null;
mesh.vertices = null;
mesh.name = MeshName;
mesh.vertices = Vertices;
mesh.triangles = Triangles;
mesh.uv = Uvs;
meshFilter.mesh = mesh;
}
private void OnDrawGizmos()
{
if (Vertices == null) return;
Gizmos.color = Color.red;
Gizmos.DrawSphere(Vector3.zero, 0.5f);
Gizmos.color = Color.blue;
for (int i = 0; i < Vertices.Length; i++)
{
Gizmos.DrawSphere(Vertices[i], 0.3f);
}
}
}
网格类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreatePlane : CreateMeshBase
{
public int xSize = 10;
public int ySize = 6;
public int widthDelta = 2;
public int heightDelta = 2;
protected override string MeshName
{
get
{
return "Plane";
}
}
protected override Vector3[] Vertices
{
get
{
Vector3[] vertices = new Vector3[(xSize + 1) * (ySize + 1)];
for (int i = 0; i < ySize+1; i++)
{
for (int j = 0; j < xSize+1; j++)
{
int index = i * (xSize + 1) + j;
vertices[index] = new Vector3(j * widthDelta, i * heightDelta, 0);
}
}
return vertices;
}
}
protected override int[] Triangles
{
get
{
int triangleCount = xSize * ySize * 2;
int[] triangle = new int[triangleCount * 3];
for (int j = 0; j < ySize; j++)
{
for (int i = 0; i < xSize; i++)
{
int squareCount = i + j * xSize;
triangle[6 * squareCount] = j * (xSize + 1) + i;
triangle[6 * squareCount + 2] = j * (xSize + 1) + i + 1;
triangle[6 * squareCount + 1] = (j + 1) * (xSize + 1) + i;
triangle[6 * squareCount + 3] = j * (xSize + 1) + i + 1;
triangle[6 * squareCount + 5