Соедините Vector3[] с сеткой в Unity
В моем проекте Unity3d я хочу создать сетку, которая соединяет четыре сферы.
Я создал новый квад и назначил массив transform.position
из моих четырех сфер в GetComponent<MeshFilter>().mesh.vertecies
моего четырехугольника.
Так как это не работает,
как я могу прочитать или записать глобальную позицию вершины в Unity?
МОЕ РЕШЕНИЕ (работает)
GameObject quad;
Transform[] spheres;
//asign values and do other stuff
void UpdateMesh(){
Vector3[] newVerts = new Vector3[spheres.Length];
for(int i = 0; i < newVerts.Length; i++){
newVerts[i] = spheres[i].position - quad.transform.position;
}
quad.GetComponent<MeshFilter>().mesh.vertecies = newVerts;
}
1 ответ
Решение
Вероятно, это зависит от того, как вы назначаете вершины.
Вот рабочий пример, с которым вы можете поэкспериментировать, просто прикрепите это как скрипт к вашему четырехугольнику:
using UnityEngine;
// adding ExecuteInEditMode attribute so we can easily see the results from the editor
[RequireComponent(typeof(MeshFilter))]
[ExecuteInEditMode]
public class VertexChanger : MonoBehaviour {
// assign these from the editor
public Transform Sphere0;
public Transform Sphere1;
public Transform Sphere2;
public Transform Sphere3;
// doing changes in update so we see this immediately from the editor
void Update () {
if (Sphere0 == null || Sphere1 == null || Sphere2 == null || Sphere3 == null) {
return;
}
// create a new array of vertices and assign it
Vector3[] newVertices = new[] {
Sphere0.transform.position,
Sphere1.transform.position,
Sphere2.transform.position,
Sphere3.transform.position
};
MeshFilter meshFilter = GetComponent<MeshFilter>();
meshFilter.sharedMesh.vertices = newVertices;
// these calls are not strictly necessary here...
meshFilter.mesh.RecalculateBounds();
meshFilter.mesh.RecalculateNormals();
}
}
Обратите внимание, что это будет работать так, как вы ожидаете, только если вы установите сферы в правильном порядке, в противном случае вам также может понадобиться пересчитать массив треугольников сетки.