- Home /
How do I calculate positions directly in front of a mesh triangle?
Hi,
I am trying to raycast from the centre of a mesh triangle in the direction that the triangle is facing.
I am able to get the middle(average) position of the triangle as the starting point of the raycast, but can't seem get the last bit, and no matter what I try, I just can't get it. Below is cleaned up code showing the triangle info and average position.
//Triangle Average positions
for (var a : int = 0; a < triangles.Count; a++)
{
var averagePosition = ((triangles[a].tri0 + triangles[a].tri1 + triangles[a].tri2) / 3);
trianglesAveragePosition.Add(averagePosition);
}
Any ideas out there? Thanks!
if you can get the direction of the normal on the triangle, you should be able to raycast in that direction. how to obtain the normal, however, I don't know.
Yes, that's one of the approaches I tried but for some reason could never get it right. I tried mesh.normals (although that can be bad apparently if the mesh is smoothed), and even calculating the dot product of the triangle myself.
Answer by robertbu · Jun 15, 2014 at 08:02 PM
Given three unique vertices, you can construct two vectors and take the cross produce. So if a, b, and c are three vertices, then it will be something like:
var v1 = b - a;
var v2 = c - b;
var normal = Vector3.Cross(v1, v2);
Note if a, b, & c are taken directly from the mesh, they will be in local coordinates, so you will have to do a 'transform.TransformDirection()' to get the world direction of the normal. In addition, I don't remember the direction of the winding of the vertices in Unity triangles, so you may have to reverse the order of the parameters in the Vector3.Cross().
Brilliant, thanks robertbu. I looked up cross and learnt the left hand rule as well, very useful!
Your answer
Follow this Question
Related Questions
Find all triangles inside given bounds 1 Answer
Weird triangle indexing problem 1 Answer
Trouble recalculating 3D mesh's triangles after deleting verts 2 Answers
Change color of mesh triangle based on Y position in world space 1 Answer
Odd Duplicate when selecting Triangle from Mesh (with Barycentric Selection.) 1 Answer