我是使用統一和 C# 的新手。我有一個關于在網格的最低 Y 坐標上生成物件的問題。
- 如何獲得具有其他坐標的最低 Y 頂點以在該點生成物件。
提前謝謝大家:)
public Mesh terrain;
public GameObject agents;
void Start()
Mesh terrain = GetComponent<MeshFilter>().mesh;
Vector3[] meshVertices = terrain.vertices;
float minY = float.MinValue;
int count = terrain.vertexCount;
List<Vector3> vertices = new List<Vector3>();
terrain.GetVertices(vertices);
for (int i = 0; i < vertices.Count; i )
{
Vector3 pos = vertices[i];
minY = Mathf.Min(pos.y,-pos.y);
Vector3 position = transform.TransformPoint(vertices[i]);
if (position.y == minY)
{
Instantiate(agents, position, Quaternion.identity);
}
}
terrain.RecalculateBounds();
uj5u.com熱心網友回復:
如果你正在尋找一個最小值,那么你需要從一個很大的東西開始,以至于任何東西都會小于那個值。類似的東西float.MaxValue。然后,您需要遍歷所有點并將當前最小值與運行最小值進行比較,如果當前點較少,則快取當前點。完成所有點后,您可以使用快取點作為實體化位置。考慮以下:
public Mesh terrain;
public GameObject agents;
void Start()
{
Mesh terrain = GetComponent<MeshFilter>().mesh;
Vector3[] meshVertices = terrain.vertices;
float minY = float.MaxValue; // <--- Change
Vector3 minimumVertex; // <--- Change
int count = terrain.vertexCount;
List<Vector3> vertices = new List<Vector3>();
terrain.GetVertices(vertices);
for (int i = 0; i < vertices.Count; i )
{
// Vector3 pos = vertices[i]; // <--- Change
// minY = Mathf.Min(pos.y,-pos.y); // <--- Change
Vector3 position = transform.TransformPoint(vertices[i]);
// if (position.y == minY) // <--- Change
if(position.y < minY) // <--- Change
{
minY = position.y; // <--- Change
minimumVertex = position; // <--- Change
//Instantiate(agents, position, Quaternion.identity); // <--- Change
}
}
Instantiate(agents, minimumVertex, Quaternion.identity); // <--- Change
terrain.RecalculateBounds();
}
uj5u.com熱心網友回復:
我一直在為您尋找一個總結大部分代碼的答案,這一切都歸功于system.linq,以下代碼按 y 坐標對頂點進行排序并將它們放在一個位置串列中,剛好足夠設定list[0]為位置。其他頂點也按順序排列,這是一個優點。
using System.Linq;
public void Start()
{
var meshFilter = GetComponent<MeshFilter>();
var list = meshFilter.mesh.vertices.Select(transform.TransformPoint).OrderBy(v => v.y).ToList();
Debug.Log(list[0]); // lowest position
Debug.Log(list.Last()); // highest position
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/488295.html
上一篇:如何根據情況在OnTriggerExit/Enter邏輯之間切換?
下一篇:如何在Unity中進行矢量加法
