版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BaiYangShouTong/article/details/53613310
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MeshPoint : MonoBehaviour {
public GameObject cubePrefab;
private Vector3[] verticals;
private List<Vector3> points;
public Transform cubeperent;
private float randomOffect;
private Vector3 pos;
private Vector3 rotation;
private float randomRotation;
private int[] triangleArr;
string triangle;
Mesh mesh;
// Use this for initialization
void Start () {
mesh = GetComponent<MeshFilter>().mesh;
cubeperent = GameObject.Find("Cubes").transform;
//*****************************************************************三角形两个顶点的中点
triangleArr = mesh.triangles;
points = new List<Vector3>(mesh.vertices);
//三角形的个数
int size = mesh.triangles.Length;
for(int i=0;i<200;i++ )
{
//一个三角形、三个点(第几个三角形)
int tt = Random.Range(0,size/3);
int index1= triangleArr[3 * tt];
int index2= triangleArr[3 * tt+1];
Debug.Log(index1+" "+index2);
//那个顶点
Vector3 point1 = points[index1];
Vector3 point2 = points[index2];
Debug.Log(point1 + " " + point2);
//中点
Vector3 point3 = (point1 +point2) / 2.0f;
Instantiate(cubePrefab, point3, Quaternion.Euler(rotation), cubeperent);
}
cubeperent.transform.position = new Vector3(0, 119.4179f, 0);
cubeperent.transform.rotation = Quaternion.Euler(new Vector3(-90.26f, 0, 0));
//----------------------------------------------------------------------------------------------------
//Debug.Log(GetComponent<MeshFilter>().mesh.vertices.Length);
//******************************************************************************************根据顶点
//verticals = GetComponent<MeshFilter>().mesh.vertices;
//points = new List<Vector3>(verticals);
//for (int j = 0; j < 400; j++)
//{
// int a = Random.Range(0, points.Count);
// randomOffect = Random.Range(-0.4f,0.4f);
// randomRotation = Random.Range(0,360);
// pos = new Vector3(points[a].x + randomOffect, points[a].y+randomOffect, points[a].z + randomOffect);
// rotation = new Vector3(transform.rotation.x + randomRotation, transform.rotation.y + randomRotation, transform.rotation.z + randomRotation);
// Instantiate(cubePrefab, pos, Quaternion.Euler(rotation), cubeperent);
// points.RemoveAt(a);
//}
//*******************************************************************************************************
cubeperent.transform.position = new Vector3(0, 119.4179f, 0);
cubeperent.transform.rotation = Quaternion.Euler(new Vector3(-90.26f, 0, 0));
}
// Update is called once per frame
void Update () {
}
}