Hi. Raycast and sweep queries return triangle index among other things. I would like to use that index to get actual vertices of the mesh.
The first thing I tried is what documentation suggests here: Unity - Scripting API: RaycastHit.triangleIndex . But as it turns out, in this example the entire mesh data is re-allocated and copied every frame. I then found a non-allocating API, but it still copies the data. There is no way I can afford that.
So is there any way to get three vectors from the actual underlying data of mesh collider? Or am I supposed to manually cache every single mesh data in managed memory to have sensible performance?
P.S. I have also found this api: Unity - Scripting API: Mesh.AcquireReadOnlyMeshData which looks like what I need. But I do not see a way to convert triangle index into vertex indices. Am I missing something?
You get both index (triangle) and vertex buffer arrays. Take any index from the index buffer, that will be the index of the vertex in the vertex buffer.
pseudocode:
var vertex = vertexbuffer[indexbuffer[i]];
A vertex is a (local) position plus additional data such as normal, tangent, color, uv and so on that may vary depending on the vertex buffer parameters.
But I get the feeling that maybe you’re overcomplicating things. What is it that you’re trying to accomplish in the end? Perhaps there are easier ways to achieve what you want.
Ah, I think I got it. Basically “index” means “triangle index” when it comes to triangle meshes. And I should be able to get triangle data from “index” array.
All I want is to get accurate surface normal (for a mesh which does not have normals pre-calculated).
Yep, “index buffer” refers to “triangle indices”.
I suppose you’re trying to follow this?
No, I am using cross product to calculate normals. This part I have no problems with. The only problem is getting those 3 vertices in the first place, without allocating 100500 bytes every frame