- Home /
How to get the vertices of a mesh face?
Can anyone point me into the right direction of how to get the vertices of a specific face of a mesh, or another way of getting the corner positions. Thanks.
A raycast will give you the index of the first point in the triangle hit (RaycastHit.triangleIndex). Assu$$anonymous$$g your faces are built out of quads, you can calculate the fourth point from the other three.
Answer by MakeCodeNow · Feb 14, 2014 at 04:23 AM
If you have the index of the face, then use Mesh.triangles to get the indices into the Mesh.vertices array.
Using that works properly for half of the face, but splits off on the other half.
http://imgur.com/a/QJ$$anonymous$$7L#0
In the first screenshot you'll notice that I am ai$$anonymous$$g to the bottom right triangle and it works perfectly, highlights just that face. However, in the second screenshot you see me ai$$anonymous$$g to the top left and things get a bit wonky. Any idea as to why this is happening, or how to force it to only get the selected face's vertices?
Here's the relevant code...
Vector3 p0 = vertices[triangles[hit.triangleIndex * 3 + 0]];
Vector3 p1 = vertices[triangles[hit.triangleIndex * 3 + 1]];
Vector3 p2 = vertices[triangles[hit.triangleIndex * 3 + 2]];
Vector3 p3 = vertices[triangles[hit.triangleIndex * 3 + 3]];
Vector3 p4 = vertices[triangles[hit.triangleIndex * 3 + 4]];
Vector3 p5 = vertices[triangles[hit.triangleIndex * 3 + 5]];
Transform hitTransform = hit.collider.transform;
p0 = hitTransform.TransformPoint(p0);
p1 = hitTransform.TransformPoint(p1);
p2 = hitTransform.TransformPoint(p2);
p3 = hitTransform.TransformPoint(p3);
p4 = hitTransform.TransformPoint(p4);
p5 = hitTransform.TransformPoint(p5);
Debug.DrawLine(p0, p1, Color.green);
Debug.DrawLine(p1, p2, Color.green);
Debug.DrawLine(p2, p0, Color.green);
Debug.DrawLine(p3, p4, Color.green);
Debug.DrawLine(p4, p5, Color.green);
Debug.DrawLine(p5, p3, Color.green);
In unity everything is triangulated, so you can't get quads, just tris. That means that in your code p0, p1, and p2 are correct, but p3, p4, and p5 are not necessarily what you think they are. They could be on another side of the mesh entirely.
Answer by wolvz38 · Sep 01, 2014 at 05:50 AM
I recently found a good way of doing this for cubes (sides are all the same). Script Reference: RaycastHit.triangleIndex
Transform hitTransform = hit.collider.transform;
int t = hit.triangleIndex * 3;
p0 = vertices[triangles[t]];
p1 = vertices[triangles[t+1]];
p2 = vertices[triangles[t+2]];
if (p1.x != p0.x) {
p3 = p2;
p3.x = p0.x;
}
if (p1.y != p0.y) {
p3 = p2;
p3.y = p0.y;
}
if (p1.z != p0.z) {
p3 = p2;
p3.z = p0.z;
}
p0 = hitTransform.TransformPoint(p0);
p1 = hitTransform.TransformPoint(p1);
p2 = hitTransform.TransformPoint(p2);
p3 = hitTransform.TransformPoint(p3);
Hope this helps anyone who has been struggling to figure this out :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613133444im_/https://answers.unity.com/themes/thub/images/avi.jpg)