Unity中實(shí)時(shí)獲取網(wǎng)格上點(diǎn)的位置,還有對(duì)應(yīng)的面和法線
在Unity中,可以使用Mesh類來獲取一個(gè)網(wǎng)格上點(diǎn)的位置以及對(duì)應(yīng)的面和法線。以下是具體步驟:
步驟一:獲取網(wǎng)格對(duì)象
在腳本中,需要先獲取要操作的網(wǎng)格對(duì)象。可以使用以下代碼:
Mesh mesh = GetComponent<MeshFilter>().mesh;
其中,GetComponent<MeshFilter>()用于獲取該游戲?qū)ο笊系腗eshFilter組件,mesh屬性用于獲取該組件的網(wǎng)格對(duì)象。
步驟二:獲取網(wǎng)格上指定點(diǎn)的位置
獲取網(wǎng)格上指定點(diǎn)的位置可以使用以下代碼:
Vector3[] vertices = mesh.vertices;
Vector3 vertexPosition = vertices[vertexIndex];
其中,vertices是網(wǎng)格的頂點(diǎn)數(shù)組,vertexIndex為指定點(diǎn)在該數(shù)組中的索引,vertexPosition為該點(diǎn)的位置。
步驟三:獲取網(wǎng)格上指定點(diǎn)所在面的法線
獲取網(wǎng)格上指定點(diǎn)所在面的法線可以使用以下代碼:
int[] triangles = mesh.triangles;
int triangleIndex = triangles[vertexIndex / 3] * 3;
Vector3[] normals = mesh.normals;
Vector3 normal = normals[triangleIndex];
其中,triangles是網(wǎng)格的三角形索引數(shù)組,vertexIndex為指定點(diǎn)在該數(shù)組中的索引,由于一個(gè)三角形包含三個(gè)頂點(diǎn),所以需要除以3來獲取該點(diǎn)所在三角形的索引。triangleIndex為該點(diǎn)所在三角形的第一個(gè)頂點(diǎn)在triangles數(shù)組中的索引,normals為網(wǎng)格的法線數(shù)組,normal為該點(diǎn)所在面的法線。
步驟四:獲取網(wǎng)格上指定點(diǎn)所在面的索引
獲取網(wǎng)格上指定點(diǎn)所在面的索引可以使用以下代碼:
int[] triangles = mesh.triangles;
int triangleIndex = triangles[vertexIndex / 3];
其中,triangles是網(wǎng)格的三角形索引數(shù)組,vertexIndex為指定點(diǎn)在該數(shù)組中的索引,由于一個(gè)三角形包含三個(gè)頂點(diǎn),所以需要除以3來獲取該點(diǎn)所在三角形的索引。
以上就是在Unity中實(shí)時(shí)獲取一個(gè)網(wǎng)格上點(diǎn)的位置以及對(duì)應(yīng)的面和法線的方法。