簡體   English   中英

Unity:在網格上尋找最低頂點

[英]Unity: Finding Lowest Vertices on Mesh

我是使用統一和 C# 的新手。 我有一個關於在網格的最低 Y 坐標上生成對象的問題。

  1. 如何獲得具有其他坐標的最低 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();

如果你正在尋找一個最小值,那么你需要從一個很大的東西開始,以至於任何東西都會小於那個值。 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();       
}

我正在為您尋找一個總結大部分代碼的答案,這一切都歸功於system.linq ,以下代碼按 y 坐標對頂點進行排序並將它們放在一個位置列表中,就足夠了 Set 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM