Search code examples
unity-game-enginerenderingmesh

Unity programmatic mesh has some smooth edges and some jagged edges


Beginner question: I'm trying to draw a "neat" triangle in a unity mesh- ie the edges look relatively even, if I make it large enough. Given a programmatically created mesh (https://catlikecoding.com/unity/tutorials/rounded-cube/), with a simple material with just a color change, I choose a few vertices on the top face and change their height:

private void DrawStuff()
{
    int width = xSize - 2;
    int height = zSize - 2;
    int margin = 5;

    int vStart = topStartVertex + (width * margin) + margin + margin;
    DrawTriangle(vStart, 10, 10, 10);
}


private void DrawTriangle(int v, int height, int width, int depth)
{
    int offset = 0;
    for (int i = 0; i < height; i++)
    {
        for (int j = 0 + offset; j < width - offset; j++)
        {
            vertices[v + i * (xSize - 1) + j][1] = ySize - depth;
        }
        offset += 1;
    }
}

However, the triangle edges don't all look the same- some are smooth, others are zig-zaggy. I would expect one or the other, but not both. I noticed the same behavior when drawing a rectangle, or even a simple line.

Is this a rendering artifact, or lighting, or something else? Is there an easy way to fix it- ie make the edges consistent, whether smooth or jagged (preferably smooth)?

I read a few other similar questions on mesh smoothing, but I think they are not the same as what I'm asking:

enter image description here


Solution

  • It's due to the mesh edges not being aligned to the edge you're trying to draw.

    In the below diagram, see that there are low altitude vertices in blue, and high altitude vertices in red (not all vertices/edges/faces are labeled for the sake of time).

    Diagram Showing the triangles and the heights of faces & vertices

    the faces that have all 3 vertices at the same height have a completely horizontal surface. Notice that since there are no mesh edges that go along the same direction as the one side of the triangle extrusion, there is a jagged appearance as there are pairs of triangles that are at the same height.

    One simply way you could fix this could be to subdivide your triangles, so that there are also edges traveling in the direction you want an edge in:

    same as above but subdivided

    But obviously, this only allows you to make edges in one more direction. And even that is more than necessary, as you could really just change how the surface is subdivided only along the parts of the extrusions as necessary:

    low poly version

    TLDR: you need mesh edges along the edges you want to make with the mesh.