- Home /
Detect a flat surface on a complex mesh?
I am trying to write a script that can detect, wether or not a given object has a flat surface somewhere on it's mesh or not.
For instance, a sphere would be a negative, where as a cube would be a positive, as this has at least one flat surface. Furthermore, a capsule would be a negative, where as a cylinder would be a positive, as the two sides of this are flat.
How do I go about doing this?
Thanks in advance.
@Vicas I am trying to find the flat surface of a mesh within a given square or rectangle area inside the mesh. Any suggestions?
Answer by Bunny83 · Jun 18, 2014 at 06:03 PM
Actually all surfaces are technically flat as all geometry is made up with triangles. However if you mean at least 1 flat-shaded surface, then you just have to compare the 3 vertex normals of each triangle. If they are equal, it's flatshaded. Something like this:
// C#
bool HasFlatshadedSurface(Mesh m)
{
Vector3[] normals = m.normals;
int[] indices = m.triangles;
int triangleCount = indices.Count / 3;
for(int i = 0; i < triangleCount; i++)
{
Vector3 n1 = normals[indices[i*3 ]];
Vector3 n2 = normals[indices[i*3 + 1]];
Vector3 n3 = normals[indices[i*3 + 2]];
if (n1 == n2 and n1 == n3)
return true;
}
return false;
}
That makes sense. I should probably have said that the surface also had to be horizontal, but from your code I can take it from there, the normals just have to be the same direction as some Vector.up I figure.
@Bunny83 Suppose if I want to know whether the area of the mesh is flat or not at which point I am raycasting with a square or rectangle boundary on it. How do I achieve this? Any suggestions?