Is there a way to get the facing direction of a mesh at a point?

Hey guys, I am looking to find the direction the mesh is facing at a point so I can spawn objects on it properly.

I tried to find the normals along the mesh verticies but that was no help, my attempt:

 Mesh mesh = obj.GetComponent<MeshFilter>().mesh;
         Vector3[] normals = mesh.normals;
         var triangles = mesh.triangles;
         Vector3 P1;
         Vector3 P2;
         Vector3 P3;
         Vector3 faceNormal;
         for (int i = 0; i < normals.Length; i++)
             //GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
             //cube.transform.position = mesh.vertices;
             P1 = normals[triangles[triangles _* 3]];_

P2 = normals[triangles[triangles * 3 + 1]];
P3 = normals[triangles[triangles * 3 + 2]];
faceNormal = ((P1 + P2 + P3) / 3);
Thanks for your help! :slight_smile:

Hi, your code is nearly correct! You need to iterate on the faces,not on the normals: change the “for” to go from 0 to (triangle.Length / 3), and with increment “i += 3” to iterate triangle by triangle (as each triangle is composed of 3 indexes to 3 vertices/normals/uv etc…)

Then, for each triangle, you will want to get the average of the 3 normals using

faceNormal = (normals[ triangle[i+0] ] + normals[ triangle[i+1] ] + normals[ triangle[i+2] ]) / 3.0f;

Then, as this “average” is an approximation, you’ll need to re-normalize the result using faceNormal.Normalize().

In fact, the result will not always be correct. It depends how the normals are defined = if the object is a smooth sphere it should be ok, but it will not work with all kind of geometry (imagine a cube with half of the vertices with “smooth” normals and the other half with normals perpendicular to each faces)

To have safer result, I suggest you compute the normal using the face vertices + a cross product: there is some documentation about this here: The code to do this is quite similar to the one here.

Edit: check this post: