Unity 中關於SubMesh的拾取問題


問題背景

最近在開發一個功能,鑽孔功能,每一層(段)都需要單獨拾取,顯示不同的顏色,使用不同材質

問題分析

對於這個功能,由於上述需求,很容易想到用submesh實現,但是主要問題是在於對於Submesh的拾取,如何知道拾取到那一段?

解決方案:

通過Unity中自帶的RaycastHit解決,里面的觸碰的三角形索引,根據三角面判斷所在Submesh。

 

上代碼

獲取鑽孔Mesh

 1         /// <summary>
 2         /// 獲取gameobject的mesh
 3         /// </summary>
 4         /// <param name="gameobject">目標物體</param>
 5         /// <returns></returns>
 6         private Mesh GetMesh(GameObject gameobject)
 7         {
 8             if (gameobject)
 9             {
10                 MeshFilter meshFilter = gameobject.GetComponent<MeshFilter>();
11                 if (meshFilter)
12                 {
13                     Mesh mesh = meshFilter.sharedMesh;
14                     if (!mesh) { mesh = meshFilter.mesh; }
15                     if (mesh)
16                     {
17                         return mesh;
18                     }
19                 }
20             }
21             return (Mesh)null;
22         }
View Code

獲取拾取Submesh索引邏輯

 1    /// <summary>
 2         /// 獲取拾取的submesh索引
 3         /// </summary>
 4         /// <param name="mesh"></param>
 5         /// <returns></returns>
 6         private int GetSubmeshIndex(Mesh mesh, RaycastHit hit)
 7         {
 8             int index = 0;
 9             if (mesh)
10             {
11                 int[] hittedTriangle = new int[]
12                 {
13                      mesh.triangles[hit.triangleIndex * 3],
14                      mesh.triangles[hit.triangleIndex * 3 + 1],
15                      mesh.triangles[hit.triangleIndex * 3 + 2]
16                 };
17                 for (int i = 0; i < mesh.subMeshCount; i++)
18                 {
19                     int[] subMeshTris = mesh.GetTriangles(i);
20                     for (int j = 0; j < subMeshTris.Length; j += 3)
21                     {
22                         if (subMeshTris[j] == hittedTriangle[0] &&
23                             subMeshTris[j + 1] == hittedTriangle[1] &&
24                             subMeshTris[j + 2] == hittedTriangle[2])
25                         {
26                             Debug.Log(string.Format("triangle index:{0} submesh index:{1} submesh triangle index:{2}", hit.triangleIndex, i, j / 3));
27                         }
28                     }
29                 }
30             }
31             return index;
32         }
View Code

 

就這樣,歡迎指正。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM